package com.crm.system.service.impl.customerManager;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.beust.jcommander.internal.Lists;
import com.crm.common.exception.FastDFSException;
import com.crm.common.model.DhPageInfo;
import com.crm.common.model.Enum.ModificationEnum;
import com.crm.common.model.Enum.ResponseCodeEnum;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.common.util.DateUtils;
import com.crm.common.util.RedisUtil;
import com.crm.dao.mapper.customerManager.QccSearchMapper;
import com.crm.model.dto.AdvancedQueryQccDto;
import com.crm.model.dto.CustomerPoolDto;
import com.crm.model.entity.cluePoolManager.Clue;
import com.crm.model.entity.cluePoolManager.ClueContact;
import com.crm.model.entity.cluePoolManager.ClueFollow;
import com.crm.model.entity.cluePoolManager.ClueVisitRecord;
import com.crm.model.entity.contactManager.Contact;
import com.crm.model.entity.contactManager.ContactInformation;
import com.crm.model.entity.contractManager.CustomerContract;
import com.crm.model.entity.customerManager.*;
import com.crm.model.entity.internalTrainingManager.CustomerUser;
import com.crm.model.entity.orderManager.CustomerProductOrder;
import com.crm.model.entity.sys.FileUpload;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.entity.sys.permissionManagement.SysCompany;
import com.crm.model.entity.systemManager.SysParameterSetting;
import com.crm.model.qo.customerManager.*;
import com.crm.model.qo.opportunityManager.OpportunityQO;
import com.crm.model.vo.cluePoolManager.ClueEditVO;
import com.crm.model.vo.cluePoolManager.ClueFollowTagVO;
import com.crm.model.vo.cluePoolManager.ClueFollowVO;
import com.crm.model.vo.contactManager.ContactInformationVO;
import com.crm.model.vo.contactManager.IndustryAreaVO;
import com.crm.model.vo.csd.customerManager.CardFrequencyVO;
import com.crm.model.vo.csd.customerManager.CustomerMemberCardDetailVO;
import com.crm.model.vo.customerContractManager.CustomerChangeCourseRecordVO;
import com.crm.model.vo.customerContractManager.CustomerContractVO;
import com.crm.model.vo.customerContractManager.exchangeVO;
import com.crm.model.vo.customerManager.*;
import com.crm.model.vo.datasearch.DataSearchResultVO;
import com.crm.model.vo.finishOrderProduct.FinishOrderProductVO;
import com.crm.model.vo.opportunityManager.OpportunityCustomerVO;
import com.crm.model.vo.productManager.CourseSubVO;
import com.crm.model.vo.productManager.CustomerMemberProductCourseVO;
import com.crm.model.vo.productManager.CustomerProductDetailVO;
import com.crm.model.vo.returnMoney.CustFinanceProductOderVO;
import com.crm.model.vo.returnMoney.ProductOfCustomerVO;
import com.crm.redis.service.customerManager.CustomerRedisService;
import com.crm.service.cluePoolManager.ClueContactDbService;
import com.crm.service.cluePoolManager.ClueDbService;
import com.crm.service.cluePoolManager.ClueFollowDbService;
import com.crm.service.cluePoolManager.ClueVisitRecordDbService;
import com.crm.service.contactManager.ContactDbService;
import com.crm.service.contactManager.ContactInformationDbService;
import com.crm.service.contractManager.CustomerContractDbService;
import com.crm.service.customerManager.*;
import com.crm.service.internalTrainingManager.CustomerUserDbService;
import com.crm.service.memberManager.MemberCardDbService;
import com.crm.service.opportunityManager.OpportunityDbService;
import com.crm.service.orderManager.CustomerProductOrderDbService;
import com.crm.service.returnMoney.FinishOrderDBservice;
import com.crm.service.sys.UserAccountDbService;
import com.crm.service.sys.permissionManagement.SysCompanyDbService;
import com.crm.service.systemManager.ParameterSettingDbService;
import com.crm.system.service.FileUploadService;
import com.crm.system.service.cluePoolManager.ClueService;
import com.crm.system.service.contactManager.ContactInformationService;
import com.crm.system.service.contactManager.ContactService;
import com.crm.system.service.customerManager.CustomerReturnService;
import com.crm.system.service.customerManager.CustomerService;
import com.crm.system.service.productManager.CustomerMemberProductCourseService;
import com.crm.system.service.productManager.CustomerMemberProductService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;

/**
 * @ Author ：pym
 * @ Date   ：2021/1/18 15:54
 */
@Slf4j
@Service
public class CustomerServiceImpl implements CustomerService {

    @Value("${esurl}")
    public String ESurl;
    @Value("${spider-url}")
    private String spiderUrl;

    @Autowired
    CustomerDbService customerDbService;

    @Autowired
    CustomerPoolDbService customerPoolDbService;

    @Autowired
    CustomerReturnService customerReturnService;

    @Autowired
    CustomerPoolRuleDbService customerPoolRuleDbService;

    @Autowired
    CustomerReceiveDbService customerReceiveDbService;

    @Autowired
    CustomerReturnDbService customerReturnDbService;

    @Autowired
    ClueService clueService;

    @Autowired
    ClueDbService clueDbService;

    @Autowired
    ClueFollowDbService clueFollowDbService;

    @Autowired
    ClueVisitRecordDbService clueVisitRecordDbService;

    @Autowired
    ClueContactDbService clueContactDbService;

    @Autowired
    ContactDbService contactDbService;

    @Autowired
    UserAccountDbService userAccountDbService;

    @Autowired
    CustomerContractDbService customerContractDbService;

    @Autowired
    CustomerProductOrderDbService customerProductOrderDbService;

    @Autowired
    FinishOrderDBservice finishOrderDBservice;

    @Autowired
    OpportunityDbService opportunityDbService;

    @Autowired
    CustomerRedisService customerRedisService;

    @Autowired
    FileUploadService fileUploadService;

    @Autowired
    CustomerReceiveDbService customerReceiveDbservice;

    @Autowired
    CustomerMemberProductService customerMemberProductService;

    @Autowired
    CustomerMemberProductCourseService memberProductCourseService;

    @Autowired
    MemberCardDbService memberCardDbService;

    @Autowired
    SysCompanyDbService sysCompanyDbService;

    @Autowired
    ContactInformationService contactInformationService;

    @Autowired
    RedisUtil redisUtil;

    //@Autowired
    //QccSearchMapper qccSearchMapper;

    @Autowired
    ParameterSettingDbService parameterSettingDbService;

    @Autowired
    ContactInformationDbService contactInformationDbService;

    @Autowired
    CustomerContactPersonDbService customerContactPersonDbService;

    @Autowired
    CustomerRelationDbService customerRelationDbService;

    @Autowired
    ContactService contactService;

    @Autowired
    CustomerProductDetailMemberCardDbService customerProductDetailMemberCardDbService;

    @Autowired
    CustomerUserDbService customerUserDbService;

    @Override
    public DhPageInfo<CustomerVO> selectCustomerVOList(Integer pageIndex, Integer pageSize, CustomerQO customerQO, String sortName, String sortOrder) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        String companyId = userAccount.getCompanyId();
        String userId = userAccount.getUserId();

        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        //增加删除状态查询条件(0:正常;1:已删除)
        customerQO.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());

        //<!--用户系统标识:用户系统客户清单只显示未领取客户--><!--管理端只显示未领取客户，超级管理员除外-->
        if (!CommonUtils.isAdmin(userId)) {
            customerQO.setUserSystemIdent("user");
        }

        StringBuilder order = new StringBuilder();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch (sortName) {
                case "customerName": {
                    order.append("customer_name ").append(sortOrder);//客户名称
                }
                break;
                case "createTm": {
                    order.append("create_tm ").append(sortOrder);
                }
                break;
                case "tag": {
                    order.append("tag ").append(sortOrder);
                }
                break;
                case "provinceName": {
                    order.append("province_name ").append(sortOrder);
                }
                break;
                case "contactPersonCount": {
                    order.append("contact_person_count ").append(sortOrder);
                }
                break;
                case "followCount": {
                    order.append("follow_count ").append(sortOrder);
                }
                break;
                default:
                    break;
            }
        }
        List<CustomerVO> customerList = customerDbService.selectCustomerList(customerQO, order.toString(), companyId);
        PageInfo<CustomerVO> pageInfo = new PageInfo<CustomerVO>(customerList);
        return new DhPageInfo<CustomerVO>(pageInfo, customerList);
    }

    @Override
    public List<String> selectCustomerIdList(String customerPoolId) {
        return customerDbService.selectCustomerIdList(customerPoolId);
    }


    /**
     * 客户详情
     *
     * @param customerPoolId 客户池id
     * @return
     */
    @Override
    public Customer selectCustomerByClueId(String customerPoolId) {
        Customer customer = customerDbService.selectCustomerByClueId(customerPoolId);
        customer.getRegistrationTime();
        return customer;
    }

    @Override
    public Boolean batchDeleteCustomerByCustomerIds(List<String> customerIds, short deleteStatus) {
        Boolean result = customerDbService.batchDeleteCustomerByCustomerIds(customerIds, deleteStatus);
        return result;
    }

    /**
     * 根据客户id查询需求分析
     *
     * @param pageIndex  页码
     * @param pageSize   分页大小
     * @param sortName   排序列名字
     * @param sortOrder  排序规则(asc/desc)
     * @param customerId 客户id
     * @return
     */
    @Override
    public DhPageInfo<DemandAnalysis> demandAnalysisList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, String customerId) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        String order = sortName + " desc";

        List<DemandAnalysis> list = customerDbService.demandAnalysisList(order, customerId);
        PageInfo<DemandAnalysis> pageInfo = new PageInfo<DemandAnalysis>(list);
        return new DhPageInfo<DemandAnalysis>(pageInfo, list);
    }

    /**
     * 客户详情-新增需求分析
     *
     * @param demandAnalysis 需求分析实体
     * @return
     */
    @Override
    public Boolean addDemandAnalysis(DemandAnalysis demandAnalysis) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        String demandAnalysisId = CommonUtils.getGUID();
        DemandAnalysis xq = new DemandAnalysis();
        xq.setDemandAnalysisId(demandAnalysisId);
        xq.setDemandAnalysisName(demandAnalysis.getDemandAnalysisName());
        xq.setSolution(demandAnalysis.getSolution());
        xq.setCreatePeopleId(userAccount.getAccountId());
        xq.setCreateTm(new Date());
        xq.setUpdatePeopleId(userAccount.getAccountId());
        xq.setUpdateTm(new Date());
        xq.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        xq.setCustomerId(demandAnalysis.getCustomerId());
        //新增联系人管理的联系人
        Boolean result = customerDbService.addDemandAnalysis(xq);
        return result;

    }

    /**
     * 根据客户Id删除客户
     *
     * @param customerId 客户Id
     * @return {@link {java.lang.Boolean}}
     * @Author pym
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Boolean deleteCustomerById(String customerId) {
        //获取当前用户
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        Customer customer = new Customer();
        customer.setCustomerId(customerId);
        customer.setUpdatePeopleId(userAccount.getAccountId());
        customer.setUpdateTm(new Date());
        customer.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.DELETE_CODE.getState())));
        customerDbService.updateCustomerById(customer);

        List<Contact> contactList = contactDbService.getContactByCustomerId(customerId);
        for (Contact contact : contactList) {
            contact.setUpdatePeopleId(userAccount.getAccountId());
            contact.setUpdateTm(new Date());
            contact.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.DELETE_CODE.getState())));
            contactDbService.deleteContactById(contact);
            List<ContactInformation> contactInformationList = contactInformationDbService.contactInformationList("create_tm desc", contact.getContactId());
            for (ContactInformation contactInformation : contactInformationList) {
                contactInformation.setUpdatePeopleId(userAccount.getAccountId());
                contactInformation.setUpdateTm(new Date());
                contactInformation.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.DELETE_CODE.getState())));
                contactInformationDbService.deleteContactInformationById(contactInformation);
            }
        }
        List<CustomerContactPerson> customerContactPersonList = customerDbService.getCustomerContactPersonByCustomerId(customerId);
        for (CustomerContactPerson customerContactPerson : customerContactPersonList) {
            customerContactPerson.setUpdatePeopleId(userAccount.getAccountId());
            customerContactPerson.setUpdateTm(new Date());
            customerContactPerson.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.DELETE_CODE.getState())));
            customerContactPersonDbService.deleteCustomerContactPersonById(customerContactPerson);
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public String retrieveCustomer(String customerId, String returnReason) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        String accountId = userAccount.getAccountId();
        Customer customer = customerDbService.selectCustomerById(customerId);
        Integer memberErrorData = customer.getMemberErrorData();
        if (memberErrorData == 2) {//客户已锁定
            return "CL0001";
        }
        //1.修改客户信息
        customer.setCustomerId(customerId);
        customer.setUpdatePeopleId(accountId);
        customer.setUpdateTm(new Date());
        customer.setCurrentStatus((short) 0);
        customer.setReceivePeopleId(null);
        customer.setAssignedPersonId(null);
        customer.setAccountId(null);
        customer.setOwnerId(null); //所有人id
        customer.setCompanyName(null); //所属公司
        Boolean result = customerDbService.updateCustomerByPrimaryKey(customer);

        if (result) {
            //2.新增客户退回记录
            customerReturnService.insertCustomerReturn(accountId, customerId, "1", returnReason);

            //3.根据客户ID更新商机所有人ID、分公司ID
            opportunityDbService.updateOpportunityByCustomerId(customerId, "", "", accountId, new Date());

            //4.根据客户ID更新联系人所有人ID、分公司ID
            contactDbService.updateContactByCustomerId(customerId, "", "", accountId, new Date());

            //5.修改客户联系人表
            customerContactPersonDbService.updateCustomerContactPersonByCustomerId(customerId, "", accountId, new Date());
        }
        return "C00000";
    }

    @Override
    public DhPageInfo<CustomerVO> selectMyCustomerList(Integer pageIndex, Integer pageSize, CustomerQO customerQO, String sortName, String sortOrder) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        String accountId = userAccount.getAccountId();
        String companyId = userAccount.getCompanyId();
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        //增加删除状态查询条件(0:正常;1:已删除)
        customerQO.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());

        Integer dateUnit = 0;
        if (!StringUtils.isBlank(customerQO.getDateType())) {
            if ("thisWeek".equals(customerQO.getDateType())) {
                //本周
                dateUnit = 1;
            }
            if ("thisMonth".equals(customerQO.getDateType())) {
                //本月
                dateUnit = 2;
            }
            if ("thisYear".equals(customerQO.getDateType())) {
                //本年
                dateUnit = 3;
            }
        }

        StringBuilder order = new StringBuilder();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch (sortName) {
                case "customerName": {
                    order.append("customer_name ").append(sortOrder);//客户名称
                }
                break;
                case "createTm": {
                    order.append("create_tm ").append(sortOrder);
                }
                break;
                case "tag": {
                    order.append("tag ").append(sortOrder);
                }
                break;
                default:
                    break;
            }
        }
        List<CustomerVO> customerList = null;
        String tabType = customerQO.getTabType();
        if (!StringUtils.isBlank(tabType)) {
            customerList = customerDbService.selectMyCustomerList(customerQO, order.toString(), dateUnit,
                    Integer.parseInt(tabType), accountId, companyId);
            PageInfo<CustomerVO> pageInfo = new PageInfo<CustomerVO>(customerList);
            return new DhPageInfo<CustomerVO>(pageInfo, customerList);
        }
        return null;
    }


    /**
     * 客户详情-修改公司简介
     *
     * @param customerCompanyInfo 公司资料实体类
     * @return
     */
    @Override
    public Boolean updateCustomerCompanyInfo(CustomerCompanyInfo customerCompanyInfo) {
        boolean result = false;
        CustomerCompanyInfo customerCompanyInfos = customerPoolDbService.getCompanyInfo(customerCompanyInfo.getCustomerId());
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        if (!StringUtils.isBlank(customerCompanyInfos.getCustomerCompanyInfoId())) {
            customerCompanyInfo.setUpdatePeopleId(userAccount.getAccountId());
            customerCompanyInfo.setUpdateTm(new Date());
            result = customerDbService.updateCustomerCompanyInfo(customerCompanyInfo);
        } else {
            CustomerCompanyInfo customerCompanyInfon = new CustomerCompanyInfo();
            String customerCompanyInfoId = CommonUtils.getGUID();
            customerCompanyInfon.setCustomerCompanyInfoId(customerCompanyInfoId);
            customerCompanyInfon.setCompanyProfile(customerCompanyInfo.getCompanyProfile());
            customerCompanyInfon.setCompanyIncome(customerCompanyInfo.getCompanyIncome());
            customerCompanyInfon.setCompanyNumber(customerCompanyInfo.getCompanyNumber());
            customerCompanyInfon.setProductServiceNumber(customerCompanyInfo.getProductServiceNumber());
            customerCompanyInfon.setFinancingSituation(customerCompanyInfo.getFinancingSituation());
            customerCompanyInfon.setUpstreamCompany(customerCompanyInfo.getUpstreamCompany());
            customerCompanyInfon.setDownstreamCompany(customerCompanyInfo.getDownstreamCompany());
            customerCompanyInfon.setCreatePeopleId(userAccount.getAccountId());
            customerCompanyInfon.setCreateTm(new Date());
            customerCompanyInfon.setUpdatePeopleId(userAccount.getAccountId());
            customerCompanyInfon.setUpdateTm(new Date());
            customerCompanyInfon.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
            customerCompanyInfon.setCustomerId(customerCompanyInfo.getCustomerId());
            result = customerDbService.addCustomerCompanyInfo(customerCompanyInfon);
        }
        return result;
    }

    /**
     * 客户详情-新增联系人-名字重复问题
     *
     * @param customerId         联系人id
     * @param contactName        联系人姓名
     * @param contactInformation 联系方式
     * @return
     */
    @Override
    public CustomerContactPerson getCustomerIdAndContactName(String customerId, String contactName, String contactInformation) {
        int mergeState = 0;
        List<CustomerContactPerson> list = customerDbService.getCustomerIdAndContactName(customerId, contactName, contactInformation);
        if (list.size() == 0) {
            return new CustomerContactPerson();
        } else {
            return list.get(0);
        }
    }

    /**
     * 竞品记录列表
     *
     * @param pageIndex  页码
     * @param pageSize   分页大小
     * @param sortName   排序列名字
     * @param sortOrder  排序规则(asc/desc)
     * @param customerId 客户id
     * @return
     */
    @Override
    public DhPageInfo<Competitor> competitorList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, String customerId) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        StringBuilder order = new StringBuilder();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch (sortName) {
                case "createTm": {
                    order.append("create_tm ").append(sortOrder);
                }
                break;
                default:
                    break;
            }
        }
        List<Competitor> customerList = customerDbService.competitorList(order.toString(), customerId);
        PageInfo<Competitor> pageInfo = new PageInfo<Competitor>(customerList);
        return new DhPageInfo<Competitor>(pageInfo, customerList);
    }

    /**
     * 新增竞品
     *
     * @param competitor 竞品实体类
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Boolean addCompetitor(Competitor competitor) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        String competitorId = CommonUtils.getGUID();
        Competitor xq = new Competitor();
        xq.setCompetitorId(competitorId);
        xq.setProductName(competitor.getProductName());
        xq.setCompetitorName(competitor.getCompetitorName());
        xq.setProductPrice(competitor.getProductPrice());
        xq.setCompetitorPrice(competitor.getCompetitorPrice());
        xq.setCompetitorUnit(competitor.getCompetitorUnit());
        xq.setCompetitorDueTime(competitor.getCompetitorDueTime());
        xq.setCurrentBudget(competitor.getCurrentBudget());
        xq.setBudgetDirector(competitor.getBudgetDirector());
        xq.setDirectorInformation(competitor.getDirectorInformation());
        xq.setCreatePeopleId(userAccount.getAccountId());
        xq.setCreateTm(new Date());
        xq.setUpdatePeopleId(userAccount.getAccountId());
        xq.setUpdateTm(new Date());
        xq.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        xq.setCustomerId(competitor.getCustomerId());
        if (!StringUtils.isBlank(competitor.getContactId())) {
            Contact contact = contactDbService.selectContactById(competitor.getContactId());
            if (contact.getContactName().equals(competitor.getBudgetDirector())
                    && contact.getContactInformation().equals(competitor.getDirectorInformation())) {
                xq.setContactId(contact.getContactId());
            } else {
                CustomerContactVO customerContactVO = new CustomerContactVO();
                customerContactVO.setCustomerId(competitor.getCustomerId());
                customerContactVO.setContactName(competitor.getBudgetDirector());
                customerContactVO.setContactInformation(competitor.getDirectorInformation());
                customerContactVO.setContactId(competitor.getContactId());
                String contactId = addCustomerContactPerson(customerContactVO);
                xq.setContactId(contactId);
            }
        } else {
            CustomerContactVO customerContactVO = new CustomerContactVO();
            customerContactVO.setCustomerId(competitor.getCustomerId());
            customerContactVO.setContactName(competitor.getBudgetDirector());
            customerContactVO.setContactInformation(competitor.getDirectorInformation());
            customerContactVO.setContactId(competitor.getContactId());
            String contactId = addCustomerContactPerson(customerContactVO);
            xq.setContactId(contactId);
        }

        //新增客户下的竞品名称
        Boolean result = customerDbService.addCompetitor(xq);
        return result;
    }

    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public String addCustomerContactPerson(CustomerContactVO customerContactVO) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        boolean rs = true;
        String contactId = "";
        String contactInformationId = CommonUtils.getGUID();

        if (!StringUtils.isBlank(customerContactVO.getExtNumber())) {
            customerContactVO.setContactInformation(customerContactVO.getContactInformation().replaceAll("-", "") + " - " + customerContactVO.getExtNumber());
        } else {
            customerContactVO.setContactInformation(customerContactVO.getContactInformation().replaceAll("-", ""));
        }

        if (!StringUtils.isBlank(customerContactVO.getContactId())) {  //有值
            //新增联系方式
            contactId = customerContactVO.getContactId();
            addContactIn(customerContactVO, contactInformationId, userAccount);
        } else {

            contactId = CommonUtils.getGUID();
            Contact contact = new Contact();
            contact.setContactId(contactId);
            contact.setContactName(customerContactVO.getContactName());
            contact.setContactPosition(customerContactVO.getContactPosition());
            contact.setContactInformation(customerContactVO.getContactInformation());
            contact.setOnTheJobSituation(customerContactVO.getOnTheJobSituation());
            contact.setProvinceId(customerContactVO.getProvinceId());
            contact.setProvinceName(customerContactVO.getProvinceName());
            contact.setCityId(customerContactVO.getCityId());
            contact.setCityName(customerContactVO.getCityName());
            contact.setIndustry(customerContactVO.getIndustry());
            contact.setCompanyAddress(customerContactVO.getCompanyAddress());
            contact.setWx(customerContactVO.getWx());
            contact.setMailBox(customerContactVO.getMailBox());
            contact.setCurrentIntention(customerContactVO.getCurrentIntention());
            contact.setFollowUpTimes(0);
            contact.setCreatePeopleId(userAccount.getAccountId());
            contact.setCreateTm(new Date());
            contact.setUpdatePeopleId(userAccount.getAccountId());
            contact.setUpdateTm(new Date());
            contact.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
            contact.setContactState(customerContactVO.getContactState());
            //contact.setMemberGrade(1);
            contact.setMemberGrade(customerContactVO.getMemberGrade());
            //contact.setMergeState(Integer.parseInt(customerContactVO.getMergeState()));
            contact.setContactNature(0);
            contact.setHomeAddress(customerContactVO.getHomeAddress());
            contact.setAbolishState(1);

            contact.setCustomerId(customerContactVO.getCustomerId());
            contact.setAccountId(userAccount.getAccountId());
            contact.setCompanyId(userAccount.getCompanyId());
            //新增联系人管理的联系人
            Boolean result = customerPoolDbService.addContact(contact);

            customerContactVO.setContactId(contactId);
            //新增联系方式
            addContactIn(customerContactVO, contactInformationId, userAccount);

            CustomerContactPerson customerContactPerson = new CustomerContactPerson();
            String customerContactPersonId = CommonUtils.getGUID();
            customerContactPerson.setCustomerContactPersonId(customerContactPersonId);
            customerContactPerson.setContactName(customerContactVO.getContactName());
            customerContactPerson.setContactPosition(customerContactVO.getContactPosition());
            customerContactPerson.setContactInformation(customerContactVO.getContactInformation());
            customerContactPerson.setOnTheJobSituation(customerContactVO.getOnTheJobSituation());
            customerContactPerson.setIsSeniorExecutive(customerContactVO.getIsSeniorExecutive());
            customerContactPerson.setMailBox(customerContactVO.getMailBox());
            customerContactPerson.setWx(customerContactVO.getWx());
            customerContactPerson.setFollowUpTimes(0);
            customerContactPerson.setCreatePeopleId(userAccount.getAccountId());
            customerContactPerson.setCreateTm(new Date());
            customerContactPerson.setUpdatePeopleId(userAccount.getAccountId());
            customerContactPerson.setUpdateTm(new Date());
            customerContactPerson.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
            customerContactPerson.setAbolishState(1);
            customerContactPerson.setContactState(customerContactVO.getContactState());
            //customerContactPerson.setMergeState(Integer.parseInt(customerContactVO.getMergeState()));
            customerContactPerson.setCustomerId(customerContactVO.getCustomerId());
            customerContactPerson.setCompanyId(userAccount.getCompanyId());
            //新增客户下的联系人
            rs = customerPoolDbService.addCustomerContactPerson(customerContactPerson);

            //联系人类型    主联系人-1   从联系人-2        目前意向   0有意向 1无意向
            if (customerContactVO.getContactState() != null && !StringUtils.isBlank(customerContactVO.getCurrentIntention())) {
                if (1 == customerContactVO.getContactState() && "0".equals(customerContactVO.getCurrentIntention())) {
                    Customer customers = customerDbService.selectCustomerById(customerContactVO.getCustomerId());
                    if (!"1".equals(customers.getPotentialCustomers())) {
                        customers.setPotentialCustomers(1);  //意向客户
                        customers.setUpdatePeopleId(userAccount.getAccountId());
                        customers.setUpdateTm(new Date());
                        customers.setAccountId(userAccount.getAccountId());
                        rs = customerPoolDbService.updateCustomer(customers);
                    }
                }
            }
        }

        return contactId;
    }

    /**
     * 新增联系方式
     *
     * @param customerContactVO
     * @param contactInformationId
     * @param userAccount
     * @return
     */
    public Boolean addContactIn(CustomerContactVO customerContactVO, String contactInformationId, UserAccount userAccount) {
        ContactInformationVO contactInformation = new ContactInformationVO();
        contactInformation.setContactInformationId(contactInformationId);
        contactInformation.setContactInformation(customerContactVO.getContactInformation());
        contactInformation.setContactType(customerContactVO.getContactType());
        //联系方式类型  0主联系方式 1从联系方式
        contactInformation.setContactInformationType(customerContactVO.getContactInformationType());
        contactInformation.setContactId(customerContactVO.getContactId());
        contactInformation.setCustomerId(customerContactVO.getCustomerId());
        contactInformation.setCreatePeopleId(userAccount.getAccountId());
        contactInformation.setCreateTm(new Date());
        contactInformation.setUpdatePeopleId(userAccount.getAccountId());
        contactInformation.setUpdateTm(new Date());
        contactInformation.setAbolishState(1);  //废止状态  1启动 2废止
        contactInformation.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        contactInformation.setCompanyId(userAccount.getCompanyId());
        Boolean rs = contactInformationService.addContactInformation(contactInformation);
        return rs;
    }

    /**
     * 联系人模块 --通过登录人查询客户列表
     *
     * @return
     */
    @Override
    public List<Customer> getCustomerList() {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        List<Customer> list = customerDbService.getCustomerList(userAccount.getAccountId());
        return list;
    }

    @Override
    public List<Customer> getMemberCustomerList() {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        List<Customer> list = customerDbService.getMemberCustomerList(userAccount.getAccountId());
        return list;
    }

    /***
     * @Description:查询所有客户列表
     * @Author: luojie
     * @Date: 2021/4/23 15:04
     */
    @Override
    public List<HashMap> getNonMemberContractCustomerList() {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        List<HashMap> list = customerDbService.getNonMemberContractCustomerList(userAccount.getAccountId());
        return list;
    }

    /**
     * 客户退回记录列表
     *
     * @param pageIndex  页码
     * @param pageSize   分页大小
     * @param sortName   排序列名字
     * @param sortOrder  排序规则(asc/desc)
     * @param customerId 客户id
     * @return
     */
    @Override
    public DhPageInfo<CustomerReturnVO> customerReturnList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, String customerId) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        StringBuilder order = new StringBuilder();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch (sortName) {
                case "returnTm": {
                    order.append("ccr.return_tm ").append(sortOrder);
                }
                break;
                default:
                    break;
            }
        }
        List<CustomerReturnVO> list = customerDbService.customerReturnList(order.toString(), customerId);
        PageInfo<CustomerReturnVO> pageInfo = new PageInfo<CustomerReturnVO>(list);
        return new DhPageInfo<CustomerReturnVO>(pageInfo, list);
    }

    /**
     * 客户领取记录列表
     *
     * @param pageIndex  页码
     * @param pageSize   分页大小
     * @param sortName   排序列名字
     * @param sortOrder  排序规则(asc/desc)
     * @param customerId 客户id
     * @return
     */
    @Override
    public DhPageInfo<CustomerReceiveVO> customerReceiveList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, String customerId) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        StringBuilder order = new StringBuilder();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch (sortName) {
                case "receiveTm": {
                    order.append("ccr.receive_tm ").append(sortOrder);
                }
                break;
                default:
                    break;
            }
        }
        List<CustomerReceiveVO> list = customerDbService.customerReceiveList(order.toString(), customerId);
        PageInfo<CustomerReceiveVO> pageInfo = new PageInfo<CustomerReceiveVO>(list);
        return new DhPageInfo<CustomerReceiveVO>(pageInfo, list);
    }

    /**
     * 客户详情商机管理
     *
     * @param pageIndex  页码
     * @param pageSize   分页大小
     * @param sortName   排序列名字
     * @param sortOrder  排序规则(asc/desc)
     * @param customerId 客户id
     * @return
     */
    @Override
    public DhPageInfo<OpportunityCustomerVO> opportunityByCustomerIdList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, String customerId) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        OpportunityQO opportunityQO = new OpportunityQO();
        opportunityQO.setCustomerId(customerId);
        opportunityQO.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        StringBuilder order = new StringBuilder();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch (sortName) {
                case "createTm": {
                    order.append("create_tm ").append(sortOrder);
                }
                break;
                default:
                    break;
            }
        }
        List<OpportunityCustomerVO> list = customerDbService.opportunityByCustomerIdList(opportunityQO);
        PageInfo<OpportunityCustomerVO> pageInfo = new PageInfo<OpportunityCustomerVO>(list);
        return new DhPageInfo<OpportunityCustomerVO>(pageInfo, list);
    }

    /**
     * 客户详情会员卡
     *
     * @param pageIndex 页码
     * @param pageSize  分页大小
     * @param sortName  排序列名字
     * @param sortOrder 排序规则(asc/desc)
     * @return
     */
    @Override
    public DhPageInfo<CardVO> selectCardByCustomerIdList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, String customerId) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        List<CardVO> list = customerDbService.selectCardByCustomerIdList(customerId);
        PageInfo<CardVO> pageInfo = new PageInfo<CardVO>(list);
        return new DhPageInfo<CardVO>(pageInfo, list);
    }

    /**
     * 查询客户下的产品
     * @param customerId   客户Id
     * @return
     */
    @Override
    public List<CustFinanceProductOderVO> selectProductByCustomerId(String customerId) {
        return finishOrderDBservice.selectProductByCustomerId(customerId);
    }

    /**
     * 查询客户下的其他联系人
     * @param customerId   客户Id
     * @return
     */
    @Override
    public List<Contact> selectOtherContactByCustomerId(String customerId, String contactId) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();

        List<Contact> list = contactDbService.selectOtherContactByCustomerId(customerId,contactId,userAccount.getAccountId(),userAccount.getCompanyId());
        return list;
    }

    /**
     * 客户详情税法直通车
     *
     * @param pageIndex 页码
     * @param pageSize  分页大小
     * @param sortName  排序列名字
     * @param sortOrder 排序规则(asc/desc)
     * @return
     */
    @Override
    public DhPageInfo<TaxCardVO> selectTaxCardByCustomerIdList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, String customerId) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        List<TaxCardVO> list = customerDbService.selectTaxCardByCustomerIdList(customerId);
        PageInfo<TaxCardVO> pageInfo = new PageInfo<TaxCardVO>(list);
        return new DhPageInfo<TaxCardVO>(pageInfo, list);
    }

    /**
     * 更新客户会员开始时间和结束时间
     */
    @Override
    public void updateCustomerMemberDate() {
        Date date = new Date();
        List<CustomerMemberDateVO> list = customerDbService.selectCustomerMemberDate();
        for(CustomerMemberDateVO cc : list) {
            Customer customer = new Customer();
            customer.setCustomerId(cc.getCustomerId());
            customer.setMembershipStartTm(cc.getContractStartDate());
            customer.setMembershipExpirationTm(cc.getContractEndDate());
            customer.setUpdateTm(date);
            customerDbService.updateCustomerById(customer);
        }
    }

    /**
     * 修改合同状态  改为已结束
     */
    @Override
    public void updateContractStatus() {
        Date date = new Date();
        List<CustomerMemberDateVO> list = customerDbService.selectContractStatus();
        for(CustomerMemberDateVO cm :list) {
            CustomerContract cc = new CustomerContract();
            cc.setContractId(cm.getContractId());
            cc.setContractStatus("3");
            cc.setUpdateTm(date);
            customerContractDbService.updateCustomerContract(cc);
        }

    }

    /**
     * 客户管理-客户详情-会员产品-会员卡
     * @param finishOrderProductNum 产品号
     * @param orderId               订单id
     * @return
     */
    @Override
    public DhPageInfo<CustomerProductDetailMemberCard> selectCardList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, String orderId, String finishOrderProductNum) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        List<CustomerProductDetailMemberCard> cardList = customerDbService.getMemberCardByOrderIdAndCph(orderId, finishOrderProductNum);
        PageInfo<CustomerProductDetailMemberCard> pageInfo = new PageInfo<CustomerProductDetailMemberCard>(cardList);
        return new DhPageInfo<CustomerProductDetailMemberCard>(pageInfo, cardList);
    }

    /**
     * 客户管理-客户详情-会员产品-税法直通车
     *
     * @param finishOrderProductNum 产品号
     * @param orderId               订单id
     * @return
     */
    @Override
    public DhPageInfo<CustomerProductDetailThroughTrainTax> selectTrainTaxList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, String orderId, String finishOrderProductNum) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        List<CustomerProductDetailThroughTrainTax> taxList = customerDbService.getThroughTrainTaxByOrderIdAndCph(orderId, finishOrderProductNum);
        PageInfo<CustomerProductDetailThroughTrainTax> pageInfo = new PageInfo<CustomerProductDetailThroughTrainTax>(taxList);
        return new DhPageInfo<CustomerProductDetailThroughTrainTax>(pageInfo, taxList);
    }

    /**
     * 客户管理-客户详情-会员产品-兑换码
     * @param finishOrderProductNum 产品号
     * @param orderId               订单id
     * @return
     */
    @Override
    public DhPageInfo<CustomerProductDetailExchangeCode> selectExchangeCodeList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, String orderId, String finishOrderProductNum) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        CustomerProductOrder customerProductOrder = customerProductOrderDbService.selectCustomerProductOrderById(orderId);
        boolean flag = false;
        //兑换码
        SimpleDateFormat sdf  =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //创建日期转换对象：年 月 日
        String date = "2021-08-01 00:00:00"; //假设 设定日期是  2018-11-11
        try {
            Date dateD = sdf.parse(date); //将字符串转换为 date 类型  Debug：Sun Nov 11 00:00:00 CST 2018
            flag = customerProductOrder.getCreateTm().getTime() < dateD.getTime();
        } catch (ParseException e1) {
            e1.printStackTrace();
        }
        List<CustomerProductDetailExchangeCode> codeList = new ArrayList<>();
        if(flag) {
             codeList = customerDbService.getExchangeCodeByOrderIdAndCph(orderId, "1");
        }else{
             codeList = customerDbService.getExchangeCodeByOrderIdAndCph(orderId, finishOrderProductNum);
        }
        PageInfo<CustomerProductDetailExchangeCode> pageInfo = new PageInfo<CustomerProductDetailExchangeCode>(codeList);
        return new DhPageInfo<CustomerProductDetailExchangeCode>(pageInfo, codeList);

    }

    /**
     * 客户管理-客户详情-会员产品-云顾问卡
     * @param finishOrderProductNum 产品号
     * @param orderId               订单id
     * @return
     */
    @Override
    public DhPageInfo<CustomerProductDetailYun> selectYunList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, String orderId, String finishOrderProductNum) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        List<CustomerProductDetailYun> yunList = customerDbService.getYunByOrderIdAndCph(orderId, finishOrderProductNum);
        PageInfo<CustomerProductDetailYun> pageInfo = new PageInfo<CustomerProductDetailYun>(yunList);
        return new DhPageInfo<CustomerProductDetailYun>(pageInfo, yunList);
    }

    /**
     * 客户管理-客户详情-会员产品-充值卡
     * @param finishOrderProductNum 产品号
     * @param orderId               订单id
     * @return
     */
    @Override
    public DhPageInfo<CustomerProductDetailRechargeCode> selectRechargeCodeList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, String orderId, String finishOrderProductNum) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        List<CustomerProductDetailRechargeCode> rechargeCodeList = customerDbService.getRechargeCodeByOrderIdAndCph(orderId, finishOrderProductNum);
        PageInfo<CustomerProductDetailRechargeCode> pageInfo = new PageInfo<CustomerProductDetailRechargeCode>(rechargeCodeList);
        return new DhPageInfo<CustomerProductDetailRechargeCode>(pageInfo, rechargeCodeList);
    }

    /**
     * 客户管理-客户详情-会员产品-优惠劵
     * @param finishOrderProductNum 产品号
     * @param orderId               订单id
     * @return
     */
    @Override
    public DhPageInfo<CustomerProductDetailCoupon> selectCouponList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, String orderId, String finishOrderProductNum) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        List<CustomerProductDetailCoupon> couponsList = customerDbService.getCouponsByOrderIdAndCph(orderId, finishOrderProductNum);
        PageInfo<CustomerProductDetailCoupon> pageInfo = new PageInfo<CustomerProductDetailCoupon>(couponsList);
        return new DhPageInfo<CustomerProductDetailCoupon>(pageInfo, couponsList);
    }

    /**
     * 每周执行一次(客户会员到期时间设置为流失客户)
     */
    @Override
    public Boolean updateLoseCustomer() {
        Date date = new Date();
        List<CustomerVO> list = customerDbService.selectMembershipExpirationTm(date);
        if(list != null && list.size() > 0) {
            for(CustomerVO cust :list) {
                Customer customer = customerDbService.selectCustomerById(cust.getCustomerId());
                if(customer.getMembershipExpirationTm() != null) {
                    customer.setUpdateTm(date);
                    customer.setLoseCustomer(1);
                    customer.setMembershipLevel(0);
                    customerDbService.updateCustomerById(customer);
                    syncES(customer,customer.getAccountId(),"客户信息-会员到期时间-改为流失客户");
                }
            }
        }

        return true;
    }

    @Override
    public void updatePotentialCustomer(String customerId) {
        Customer customer = customerDbService.selectCustomerById(customerId);
        customer.setPotentialCustomers(0);
        customerDbService.updateCustomerById(customer);
        syncES(customer,customer.getAccountId(),"修改为无意向客户");
    }

    @Override
    public void updatePotentialCustomerOne(String customerId) {
        Customer customer = customerDbService.selectCustomerById(customerId);
        customer.setPotentialCustomers(1);
        customerDbService.updateCustomerById(customer);
        syncES(customer,customer.getAccountId(),"修改为意向客户");
    }

    /**
     * ES同步客户信息
     * @param customer
     */
    @Override
    public void syncESCustomerMembershipLevel(Customer customer) {
        syncES(customer,customer.getAccountId(),"客户信息-客户会员等级");
    }

    /**
     * 每周执行一次(会员最大合同到期时间设置为客户会员到期时间)
     * @return
     */
    @Override
    public Boolean updateCustomerMembershipExpirationTm() {
        try{
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(date);
            Date newDate = sdf.parse(format);

            List<CustomerContractVO> list = customerDbService.selectContractEndDate();
            if(list != null && list.size() > 0) {
                for(CustomerContractVO contractVO :list) {
                    Customer customer = customerDbService.selectCustomerById(contractVO.getCustomerId());
                    if(customer != null) {
                        //大于 等于
                        if (contractVO.getContractEndDate().after(newDate) || contractVO.getContractEndDate().equals(newDate)) {
                            log.info(sdf.format(contractVO.getContractEndDate()) + "大于" + sdf.format(newDate));
                            customer.setMembershipLevel(2);
                            customer.setLoseCustomer(null);
                        }

                        //小于
                        if (contractVO.getContractEndDate().before(newDate)) {
                            log.info(sdf.format(contractVO.getContractEndDate()) + "小于" + sdf.format(newDate));
                            customer.setMembershipLevel(0);
                            customer.setLoseCustomer(1);
                        }

                        customer.setMembershipExpirationTm(contractVO.getContractEndDate());
                        customer.setUpdateTm(date);
                        customerDbService.updateCustomerByIdSql(customer);
                        syncES(customer,customer.getAccountId(),"客户信息-会员合同到期时间-改为客户会员到期时间");
                    }
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 客户公海-客户清单-领取
     *
     * @param customerId          客户id
     * @param customerPoolId      客户池id
     * @param nature              性质：1-全国公有池；2-分公司公有池；
     * @param affiliatedCompanyId 全国公有池关联公司id
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public String receiveCustomer(String customerId, String customerPoolId, String nature, String affiliatedCompanyId) {
        Customer customer = customerDbService.selectCustomerById(customerId);
        Integer memberErrorData = customer.getMemberErrorData();
        if (memberErrorData == 2) {//客户已锁定
            return "C00008";
        }
        //我的客户最大容量
        SysParameterSetting sysParameterSetting = parameterSettingDbService.selectSystemParameterSetting();
        int maxCount = sysParameterSetting != null ? sysParameterSetting.getMaxCustomerNum() : 0;
        //long maxCount = 200;
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登陆人信息
        String accountId = userAccount.getAccountId();
        String companyId = userAccount.getCompanyId();
        //一、当前客户状态是否未领取。
        Boolean isReceived = customerDbService.checkCustomerIsReceived(customerId);
        if (!isReceived) {
            return "C00001";
        }
        //二、我的客户非会员客户数量是否超过175个
        //根据用户id查询我的客户非会员客户数量
        long count = customerDbService.selectNonmemberCustomerCountByAccountId(accountId);
        if (count >= maxCount) {
            return "C00002";
        }
        //当前客户池领取规则
        CustomerPoolRule customerPoolRule = customerPoolRuleDbService.selectCustomerPoolRuleReceive(customerPoolId);
        if (customerPoolRule != null) {
            //三、客户领取量是否超过该池设置的最大领取量   超过该池最大领取量
            long customerReceiveCount = customerReceiveDbService.selectCustomerReceiveCount(accountId, customerPoolId);
            if (customerReceiveCount >= customerPoolRule.getCustomerPoolNumber()) {
                return "C00003";
            }
            //同一客户释放或者收回的最新一条记录信息
            CustomerReturn customerReturn = customerReturnDbService.selectCustomerReturnNew(customerId);
            //四、同一客户是否满足(释放 收回)时间间隔  小时
            if (customerReturn != null) {
                Date returnTm = customerReturn.getReturnTm();
                //全国公有池-其它公司时间限制(其它公司比所属公司领取时间间隔长)
                if ("1".equals(nature) && StringUtils.isNotBlank(affiliatedCompanyId) && !affiliatedCompanyId.equals(companyId)) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(returnTm);
                    Integer timeLimit = customerPoolRule.getTimeLimit();
                    calendar.add(Calendar.HOUR, timeLimit != null ? timeLimit : 0);
                    returnTm = calendar.getTime();
                    Date currentTime = new Date();
                    if (!returnTm.before(currentTime)) {
                        return "C00007";
                    }
                }
                //同一客户是否满足(释放 收回)时间间隔  小时
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(returnTm);
                calendar.add(Calendar.HOUR, customerPoolRule.getTimeInterval());
                returnTm = calendar.getTime();
                Date currentTime = new Date();
                if (!returnTm.before(currentTime)) {
                    return "C00004";
                }
            }
            //同一客户领取的最新一条记录信息
            CustomerReceive customerReceive = customerReceiveDbService.selectCustomerReceiveNew(accountId, customerPoolId);
            //五、同一客户池客户的领取时间间隔是否满足
            if (customerReceive != null) {
                Date receiveTm = customerReceive.getReceiveTm();
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(receiveTm);
                calendar.add(Calendar.SECOND, customerPoolRule.getAnyTimeInterval());
                receiveTm = calendar.getTime();
                Date currentTime = new Date();
                if (!receiveTm.before(currentTime)) {
                    return "C00005";
                }
            }
        }
        //六、更新客户状态
        updateCustomer(customerId, accountId, companyId);

        //七、插入领取记录
        insertCustomerReceive(customerId, customerPoolId, accountId, 1);

        //八、根据客户ID更新商机所有人ID、分公司ID
        opportunityDbService.updateOpportunityByCustomerId(customerId, accountId, companyId, accountId, new Date());

        //九、根据客户ID更新联系人所有人ID、分公司ID
        contactDbService.updateContactByCustomerId(customerId, accountId, companyId, accountId, new Date());

        //十、修改客户联系人表
        customerContactPersonDbService.updateCustomerContactPersonByCustomerId(customerId, companyId, accountId, new Date());
        return "C00006";
    }

    /**
     * 客户公海-客户调转-领取
     *
     * @param customerId       客户id
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public String receiveCustomerAround(String customerId) {
        //默认放入 全国默认池，查询默认池id
        CustomerPoolDto poolDto = customerPoolDbService.selectPoolByName("全国默认池");
        if (poolDto==null){
            //客户池不存在
            log.info("-----客户公海-客户调转-领取:【客户池不存在】-------");
            return "C00001";
        }
        //一、判断客户池中现有数据量是否超出全国默认池配置的最大可放入数量
        int customerCount = customerDbService.selectCountById(poolDto.getId());
        if (customerCount>=poolDto.getCapacity()){
            //全国池已满
            log.info("-----客户公海-客户调转-领取:【全国池已满】-------");
            return "C00002";
        }

        //我的客户最大容量
        SysParameterSetting sysParameterSetting = parameterSettingDbService.selectSystemParameterSetting();
        int maxCount = sysParameterSetting != null ? sysParameterSetting.getMaxCustomerNum() : 0;
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登陆人信息
        String accountId = userAccount.getAccountId();
        //二、我的客户非会员客户数量是否超过175个
        //根据用户id查询我的客户非会员客户数量
        long count = customerDbService.selectNonmemberCustomerCountByAccountId(accountId);
        if (count >= maxCount) {
            //客户最大领取数量已满
            log.info("-----客户公海-客户调转-领取:【业务员最大领取数量已满】,业务员id{}-------",accountId);
            return "C00003";
        }

        String result=null;
        //三、查询spider项目获取详细数据。判断是否已领取
        Map<String,Object> map=new HashMap<>();
        map.put("id",customerId);
        result = HttpUtil.post(spiderUrl + "/qcc/selectById", map);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String code = jsonObject.getString("code");
        AdvancedQueryQccDto advancedQueryQccDto=null;
        if ("000000".equals(code)){
            String data = jsonObject.getString("data");
            if (data!=null){
                advancedQueryQccDto = JSONObject.parseObject(data, AdvancedQueryQccDto.class);
                Integer isReceive = advancedQueryQccDto.getIsReceive();
                //已被领取
                if (1==isReceive) {
                    log.info("-----客户公海-客户调转-领取:【该客户已被领取】,客户id{}-------",customerId);
                    return "C00004";
                }
            }else {
                //数据异常
                log.info("-----客户公海-客户调转-领取:【未查出此数据】,客户id{}-------",customerId);
                return "C00000";
            }
        }else {
            //请求失败
            log.info("-----客户公海-客户调转-领取:【http查询请求失败】,客户id{},http返回数据:{}-------",customerId,result);
            return "C00000";
        }

        String enterpriseName = advancedQueryQccDto.getEnterpriseName();//公司名
        String socialCode = advancedQueryQccDto.getSocialCode();//社会统一信用代码
        //四、redis校验数据
        String redisValue = redisUtil.get("customer_library:"+enterpriseName);
        log.info("-----客户公海-客户调转-领取:【redis数据】:公司名:{},统一信用代码:{}-------",enterpriseName,redisValue);
        if (StringUtils.isNotBlank(redisValue)){
            if(!socialCode.equals(redisValue)){
                //数据有误,检查企查查社会统一信用代码
                log.info("-----客户公海-客户调转-领取:【redis数据校验失败】,客户id:{},公司名:{},统一信用代码:{}-------",customerId,enterpriseName,socialCode);
                return "C00005";
            }
        }


        //五、mysql校验数据
        int i = customerDbService.selectCountByNameByCode(enterpriseName, socialCode);
        if (i!=0){
            log.info("-----客户公海-客户调转-领取:【mysql数据重复】:公司名:{},统一信用代码:{}-------",enterpriseName,socialCode);
            //数据重复 将数据修改为已领取
            String updateResults = HttpUtil.post(spiderUrl + "/qcc/receiveById", map);
            JSONObject updateJsonObject = JSONObject.parseObject(updateResults);
            String updateCode = updateJsonObject.getString("code");
            if (!"000000".equals(updateCode)){
                throw new RuntimeException("---修改spider项目数据失败---客户Id【"+accountId+"】");
            }
            return "000000";
        }

        //六 客户表、领取记录表插入数据、redis插入、同步es
        Customer customer = handleObject(advancedQueryQccDto,accountId,poolDto.getId());
        customerDbService.insertCustomer(customer);//插入客户池
        insertCustomerReceive(customer.getCustomerId(),poolDto.getId(),accountId,1);//插入领取记录
        customerRedisService.setCustomerByNameAndCode(customer);//将客户信息插入Redis
        // sync ES
        syncES(customer,accountId,"客户调转-新增企业客户");

        //七 向spider发送请求，将状态改为领取
        String updateResults = HttpUtil.post(spiderUrl + "/qcc/receiveById", map);
        JSONObject updateJsonObject = JSONObject.parseObject(updateResults);
        String updateCode = updateJsonObject.getString("code");
        if (!"000000".equals(updateCode)){
            throw new RuntimeException("---修改spider项目数据失败---客户Id【"+accountId+"】");
        }
        return "000000";
    }

    @Override
    public DhPageInfo<CustomerTransferRecordVo> customerTransferRecordList(Integer pageIndex, Integer pageSize, String customerName) {
        PageHelper.startPage(pageIndex,pageSize);
        List<CustomerTransferRecordVo> voList = customerDbService.selectCustomerTransferRecordList(customerName);
        PageInfo<CustomerTransferRecordVo> pageInfo = new PageInfo<>(voList);
        return new DhPageInfo<CustomerTransferRecordVo>(pageInfo, voList);
    }

    /**
     * 企查查数据组装
     * @param dto 企查查数据
     * @param accountId 业务员id
     * @param poolId 客户池id
     * @return
     */
    private Customer handleObject(AdvancedQueryQccDto dto,String accountId,String poolId){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Customer customer=new Customer();
        Date date=new Date();
        customer.setCustomerId(CommonUtils.getGUID());
        customer.setCustomerNumber(createCustomerNumber());
        customer.setCreateTm(date);
        customer.setUpdateTm(date);
        customer.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        //客户来源（客户调转）
        customer.setCustomerSource("12");
        //客户类型
        customer.setCustomerType("0");
        //客户名称
        customer.setCustomerName(dto.getEnterpriseName());
        //统一信用代码
        customer.setUnifiedSocialCreditCode(dto.getSocialCode());
        //客户行业
        customer.setCustomerIndustryFirst(dto.getIndustryType());
        //所属省
        customer.setProvinceName(dto.getProvice());
        //所属市
        customer.setCityName(dto.getCity());
        //所属区
        customer.setCountyName(dto.getDistrict());
        //详细地址
        customer.setDetailedAddress(dto.getEnterpriseAddress());
        //企业对外手机 -> 电话
        customer.setEnterpriseExternalPhone(dto.getPhone());
        //企业对外座机 -> 更多电话
        customer.setEnterpriseExternalLandline(dto.getMorePhone());
        //公司网址
        customer.setCompanyWebsite(dto.getWebsite());
        //注册号
        customer.setRegistrationNumber(dto.getRegistCode());
        //组织机构代码
        customer.setOrganizationCode(dto.getOrgCode());
        //企业类型
        customer.setCompanyType(dto.getEnterpriseType());
        //法定代表人
        customer.setLegalRepresentative(dto.getLegalPerson());
        //注册资本
        if (StringUtils.isNotBlank(dto.getRegistCapital())){
            if (dto.getRegistCapital().contains("万")){
                String[] split = dto.getRegistCapital().split("万");
                customer.setRegisteredCapital(split[0]);
            }else {
                customer.setRegisteredCapital(dto.getRegistCapital());
            }
        }
        //注册时间
        if (StringUtils.isNotBlank(dto.getEstablishDate()) && !"-".equals(dto.getEstablishDate())){
            try {
                customer.setRegistrationTime(sdf.parse(dto.getEstablishDate()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        //经营范围
        customer.setBusinessScope(dto.getBusiness());
        //企业状态
        customer.setEnterpriseState(dto.getRegistStatus());
        //参保人数
        try {
            if (StringUtils.isNotBlank(dto.getInsuredTotal())){
                customer.setInsuredNumber(Integer.valueOf(dto.getInsuredTotal()));
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        //邮箱
        customer.setEmail(dto.getEmail());
        //系统标签
        customer.setSystemTag(dto.getSysTag());
        //创建人
        customer.setCreatePeopleId(accountId);
        //用户id
        customer.setAccountId(accountId);
        //领取人id
        customer.setReceivePeopleId(accountId);
        //客户池
        customer.setCustomerPoolId(poolId);
        //目前状态(已领取)
        customer.setCurrentStatus(Short.valueOf(1+""));
        //所有人
        customer.setOwnerId(accountId);
        return customer;
    }

    /**
     * 更新客户状态
     *
     * @param customerId
     * @param accountId
     * @param companyId
     */
    private void updateCustomer(String customerId, String accountId, String companyId) {
        Customer customer = new Customer();
        customer.setCustomerId(customerId);
        customer.setCurrentStatus(Short.parseShort("1"));
        customer.setReceivePeopleId(accountId);
        customer.setAccountId(accountId);
        customer.setUpdateTm(new Date());
        customer.setUpdatePeopleId(accountId);
        customer.setAssignedPersonId("");
        customer.setOwnerId(accountId); //所有人id
        customer.setCompanyName(companyId); //所属公司
        customerDbService.updateCustomerById(customer);

    }

    /**
     * 插入领取记录
     *
     * @param customerId
     * @param customerPoolId
     * @param accountId
     */
    private void insertCustomerReceive(String customerId, String customerPoolId, String accountId, Integer receiveWay) {
        CustomerReceive customerReceive = new CustomerReceive();
        customerReceive.setCustomerReceiveId(CommonUtils.getGUID());
        customerReceive.setReceivePeopleId(accountId);
        customerReceive.setReceiveTm(new Date());
        customerReceive.setReceiveWay(receiveWay);
        customerReceive.setCustomerPoolFromId(customerPoolId);
        customerReceive.setCustomerId(customerId);
        customerReceiveDbService.insertCustomerReceive(customerReceive);
    }

    @Override
    public Map<String, String> addCustomer(CustomerAddQO customerAddQO) {
        Map<String, String> map = new HashMap<String, String>();
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        String companyId = userAccount.getCompanyId();
        CustomerPool customerPool = null;
        //我的客户最大容量
        SysParameterSetting sysParameterSetting = parameterSettingDbService.selectSystemParameterSetting();
        int maxCount = sysParameterSetting != null ? sysParameterSetting.getMaxCustomerNum() : 0;
        String accountId = userAccount.getAccountId();
        //根据用户id查询我的客户非会员客户数量
        long customerCount = customerDbService.selectNonmemberCustomerCountByAccountId(accountId);
        if (customerCount >= maxCount) {
            map.put("code", "C00004");
            map.put("customerId", "");
            //超出我的客户容量
            return map;
        }
        //1、查询客户池容量
        //客户池id
        //String customerPoolId = customerAddQO.getCustomerPoolId();
        //客户名称
        String customerName = CommonUtils.removeCharacters(customerAddQO.getCustomerName()).replaceAll("\\(", "（").replaceAll("\\)", "）");
        customerAddQO.setCustomerName(customerName);
        //统一社会信用代码
        String unifiedSocialCreditCode = customerAddQO.getUnifiedSocialCreditCode();
        //先通过客户名称查询redis
        String redisValue = redisUtil.get("customer_library:"+customerName);
        log.info("查询redis公司名称【{}】返回的社会统一信用代码是【{}】",customerName,redisValue);
        if(StringUtils.isNotBlank(redisValue)){
            //查询redis不为空，对比redis的社会信用代码
            if(!unifiedSocialCreditCode.equals(redisValue)){
                map.put("code","C00404");
                map.put("message","输入的社会信用代码不正确！");
                return map;
            }
        }else{
            //查询redis查不到 再 通过社会信用代码调用企查查的企业工商信息核验接口
            String responseCode = clueService.getVerification(customerName, unifiedSocialCreditCode);
            if (!"200".equals(responseCode)) {
                System.out.println("查询工商核验信息失败··········");
                map.put("code", "C00201");//表示核验失败
                map.put("message", "输入的企业信息有误，请核实！");
                return map;
            }
        }

        //根据客户池id查询客户池信息
        //CustomerPool customerPool = customerPoolDbService.selectCustomerPoolById(customerPoolId);
        //根据公司id查询客户池信息
        if (StringUtils.isNotBlank(companyId)) {
            customerPool = customerPoolDbService.selectCustomerPoolCompanyId(companyId);
        }
        if (customerPool == null) {
            //所属公司对应的全国公有池不存在
            map.put("code", "C00003");
            map.put("customerId", "");
            return map;
        }
        //客户池容量
        int capacity = customerPool.getCapacity();
        String customerPoolId = customerPool.getCustomerPoolId();
        customerAddQO.setCustomerPoolId(customerPoolId);

        //查询客户池已经存在的客户数
        long count = customerDbService.selectCustomerCount(customerPoolId);
        if (count < capacity) {
            Boolean result = customerRelationDbService.selectCustomerRelationByName(customerName);
            if (result) {//客户关联表已存在，客户名称已关联客户
                map.put("code", "C00005");
                map.put("customerId", "");
                return map;
            }
            Boolean isCustomerRepeat = customerDbService.selectCustomerIfRepeated(customerName, unifiedSocialCreditCode);
            if (!isCustomerRepeat) {
                Customer customer = getCustomer(customerAddQO);
                customerDbService.insertCustomer(customer);
                customerRedisService.setCustomerByNameAndCode(customer);//将客户信息插入Redis
                map.put("code", "C00000");
                map.put("customerId", customer.getCustomerId());

                // sync ES
                syncES(customer,accountId,"新增企业客户");

                return map;
                //保存成功
                //return "C00000";
            } else {
                map.put("code", "C00002");
                map.put("customerId", "");
                //客户名称和统一社会信用代码已存在
                //return "C00002";
                return map;
            }
        } else {
            map.put("code", "C00001");
            map.put("customerId", "");
            //超出客户池容量
            //return "C00001";
            return map;
        }

    }


    private Customer getCustomer(CustomerAddQO customerAddQO) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        String accountId = userAccount.getAccountId();
        Customer customer = new Customer();
        customer.setCustomerId(CommonUtils.getGUID());
        customer.setCustomerName(customerAddQO.getCustomerName());
        customer.setCustomerNumber(createCustomerNumber());
        customer.setCustomerType(customerAddQO.getCustomerType());
        customer.setCustomerLevel(customerAddQO.getCustomerLevel());
        customer.setUnifiedSocialCreditCode(customerAddQO.getUnifiedSocialCreditCode());
        customer.setOriginalCustomerId(customerAddQO.getOriginalCustomerId());
        customer.setCustomerIndustryFirst(customerAddQO.getCustomerIndustryFirst());
        customer.setCustomerIndustrySecond(customerAddQO.getCustomerIndustrySecond());
        customer.setProvinceCode(customerAddQO.getProvinceCode());
        customer.setProvinceName(customerAddQO.getProvinceName());
        customer.setCityCode(customerAddQO.getCityCode());
        customer.setCityName(customerAddQO.getCityName());
        customer.setCountyCode(customerAddQO.getCountyCode());
        customer.setCountyName(customerAddQO.getCountyName());
        customer.setDetailedAddress(customerAddQO.getDetailedAddress());
        customer.setEnterpriseExternalPhone(customerAddQO.getEnterpriseExternalPhone());
        customer.setEnterpriseExternalLandline(customerAddQO.getEnterpriseExternalLandline());
        customer.setCompanyWebsite(customerAddQO.getCompanyWebsite());
        customer.setCompanySize(customerAddQO.getCompanySize());
        customer.setRegistrationNumber(customerAddQO.getRegistrationNumber());
        customer.setOrganizationCode(customerAddQO.getOrganizationCode());
        customer.setCompanyType(customerAddQO.getCompanyType());
        customer.setLegalRepresentative(customerAddQO.getLegalRepresentative());
        customer.setRegisteredCapital(customerAddQO.getRegisteredCapital());
        customer.setRegistrationTime(customerAddQO.getRegistrationTime());
        customer.setEnterpriseState(customerAddQO.getEnterpriseState());
        customer.setCapitalType(customerAddQO.getCapitalType());
        customer.setInsuredNumber(customerAddQO.getInsuredNumber());
        customer.setFax(customerAddQO.getFax());
        customer.setEmail(customerAddQO.getEmail());
        customer.setRemark(customerAddQO.getRemark());
        customer.setFinancialNumber(customerAddQO.getFinancialNumber());  //财务人数
        customer.setCreatePeopleId(accountId);
        customer.setCreateTm(new Date());
        customer.setUpdatePeopleId(accountId);
        customer.setUpdateTm(new Date());
        customer.setAccountId(accountId);
        Short currentStatus = customerAddQO.getCurrentStatus();
        if (currentStatus != 0) {//目前状态---0: 未领取; 1: 已领取(我领取的客户);2: 已分配(分配给我的客户);3: 自建客户(用户模块我自建的客户);
            customer.setOwnerId(accountId);
            customer.setCompanyName(userAccount.getCompanyId());
            if (currentStatus == 1) {
                customer.setReceivePeopleId(accountId);
            }
            if (currentStatus == 2) {
                customer.setAssignedPersonId(accountId);
            }
        }
        customer.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));

        customer.setCustomerSource(customerAddQO.getCustomerSource());
        //customer.setCustomerState(customerAddQO.getCustomerState());
        customer.setIndustry(customerAddQO.getIndustry());
        customer.setDealStatus(customerAddQO.getDealStatus());
        customer.setUploadId(customerAddQO.getUploadId());
        customer.setCustomerPoolId(customerAddQO.getCustomerPoolId());
        customer.setBusinessScope(customerAddQO.getBusinessScope());
        customer.setTag(customerAddQO.getTag());
        customer.setCurrentStatus(currentStatus);

        customer.setContactPerson(customerAddQO.getContactPerson());
        customer.setContactPersonPhone(customerAddQO.getContactPersonPhone());
        return customer;
    }


    @Override
    public Boolean updateCustomerState(String customerId, String customerState) {
        /*//获取当前用户
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        Customer customer = new Customer();
        customer.setCustomerId(customerId);
        customer.setCustomerState(customerState);
        customer.setUpdatePeopleId(userAccount.getAccountId());
        customer.setUpdateTm(new Date());
        return customerDbService.updateCustomerById(customer);*/
        return null;
    }

    /**
     * 用户-线索管理-我的线索池-线索清单-转化为客户
     *
     * @param clueId 线索id
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public String convertToCustomer(String clueId) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        String customerId = CommonUtils.getGUID();
        //查询线索详情
        ClueEditVO clueEditVO = clueService.selectClueByClueId(clueId);
        //去重 查询客户是否一样 通过线索的公司名称和统一社会信用码查询有没有这个客户
        Clue clue = new Clue();
        //线索表插入数据    线索状态clueState  3已转化   客户Id
        clue.setClueId(clueId);
        clue.setClueState(3); //已转化
        clue.setCustomerId(customerId); //客户id
        clue.setConversionTime(new Date()); //转化时间
        clue.setUpdateTm(new Date()); //更新时间
        //调用企查查核验接口
        String verificationCode = clueService.getVerification(clueEditVO.getCompanyName(), clueEditVO.getUnifiedSocialCreditCode());
        if (!"200".equals(verificationCode)) {
            return "C00030";
        }
        Boolean result = customerRelationDbService.selectCustomerRelationByName(clueEditVO.getCompanyName());
        if (result) {//客户关联表已存在，客户名称已关联客户
            return "CF0004";
        }

        Boolean rs = customerDbService.customerIdAndUnifiedSocialCreditCode(clueEditVO.getCompanyName(), clueEditVO.getUnifiedSocialCreditCode(), userAccount.getAccountId());
        if (rs) {
            //我的客户最大容量
            SysParameterSetting sysParameterSetting = parameterSettingDbService.selectSystemParameterSetting();
            int maxCount = sysParameterSetting != null ? sysParameterSetting.getMaxCustomerNum() : 0;
            String accountId = userAccount.getAccountId();
            //根据用户id查询我的客户非会员客户数量
            long customerCount = customerDbService.selectNonmemberCustomerCountByAccountId(accountId);
            if (customerCount >= maxCount) {
                return "CF0002";
            } else {
                //新建客户
                Customer customer = new Customer();
                customer.setCustomerId(customerId);
                customer.setCustomerName(clueEditVO.getCompanyName());  //线索--公司名称-->客户名称
                customer.setContactPerson(clueEditVO.getContactPerson());  //线索--联系人-->联系人
                customer.setContactPersonPhone(clueEditVO.getContactPersonPhone());  //线索--联系方式-->联系方式
                customer.setEmail(clueEditVO.getCompanyEmail());  //线索--公司邮箱-->邮箱
                customer.setCustomerType("0");//线索--客户类别-->客户类型
                //customer.setCustomerLevel(clueEditVO.getClientLevel());//线索--客户级别-->客户级别
                customer.setUnifiedSocialCreditCode(clueEditVO.getUnifiedSocialCreditCode());//线索--社会信用码-->统一社会信用代码
                customer.setIndustry(clueEditVO.getIndustry());//线索--行业-->行业
                customer.setCompanySize(clueEditVO.getCompanySize());//线索--公司规模-->公司规模
                customer.setCompanyWebsite(clueEditVO.getCompanyWebsite());//线索--公司网址-->公司网址
                customer.setRegistrationNumber(clueEditVO.getRegistrationNumber());//线索--注册号-->注册号
                customer.setOrganizationCode(clueEditVO.getOrganizationCode());//线索--组织机构代码-->组织机构代码
                customer.setCompanyType(clueEditVO.getCompanyType());//线索--公司类型-->公司类型
                customer.setLegalRepresentative(clueEditVO.getLegalRepresentative());//线索--法定代表人-->法定代表人
                customer.setEnterpriseExternalPhone(clueEditVO.getEnterpriseExternalPhone());//线索--对外手机-->企业对外手机
                customer.setEnterpriseExternalLandline(clueEditVO.getEnterpriseExternalLandline());//线索--对外座机-->企业对外座机

                if ("0".equals(String.valueOf(clueEditVO.getRegisteredCapital())) || "null".equals(String.valueOf(clueEditVO.getRegisteredCapital())) || clueEditVO.getRegisteredCapital() <= 0) {
                    customer.setRegisteredCapital("");//线索--注册资本-->注册资本
                } else {
                    customer.setRegisteredCapital(String.valueOf(clueEditVO.getRegisteredCapital()));//线索--注册资本-->注册资本
                }
                customer.setProvinceCode(clueEditVO.getProvinceId());
                customer.setProvinceName(clueEditVO.getProvinceName());
                customer.setCityCode(clueEditVO.getCityId());
                customer.setCityName(clueEditVO.getCityName());
                customer.setRegistrationTime(clueEditVO.getRegistrationTime());//线索--注册时间-->注册时间
                customer.setCapitalType(clueEditVO.getCapitalType());//线索--资本类型-->资本类型
                customer.setEnterpriseState(clueEditVO.getEnterpriseState());//线索--企业状态-->企业状态
                customer.setInsuredNumber(clueEditVO.getInsuredNumber());//线索--参保人数-->参保人数
                customer.setTag(clueEditVO.getTag());//线索--标签-->标签
                //customer.setCityName(clueEditVO.getCityName());//线索--城市名称-->城市名称
                customer.setBusinessScope(clueEditVO.getBusinessScope());//线索--经营范围-->经营范围
                customer.setRemark(clueEditVO.getRemark());//线索--备注-->备注
                customer.setCurrentStatus(Short.parseShort(String.valueOf("1")));//已领取
                customer.setCreatePeopleId(userAccount.getAccountId());
                customer.setCreateTm(new Date());
                customer.setUpdatePeopleId(userAccount.getAccountId());
                customer.setUpdateTm(new Date());
                customer.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
                customer.setAccountId(userAccount.getAccountId());
                customer.setReceivePeopleId(userAccount.getAccountId());
                CustomerPool customerPool = customerPoolDbService.selectCustomerPoolByName("全国默认池");
                if (customerPool != null) {
                    customer.setCustomerPoolId(customerPool.getCustomerPoolId());
                }
                customer.setOwnerId(userAccount.getAccountId()); //所有人id
                customer.setCompanyName(userAccount.getCompanyId()); //所属公司
                customerDbService.insertCustomer(customer);

                // 插入ES
                syncES(customer,userAccount.getAccountId(),"线索池转客户");

                //插入跟进记录表  客户Id  先查询出线索下的跟进记录
                List<ClueFollow> clueFollowList = clueFollowDbService.selectClueFollowList(clueId);
                if (clueFollowList != null || clueFollowList.size() > 0) {
                    for (ClueFollow clueFollow : clueFollowList) {
                        clueFollow.setCustomerId(customerId);
                        clueFollowDbService.updateClueFollow(clueFollow);
                    }
                }

                //插入拜访记录表  客户Id  先查询出线索下的拜访记录
                List<ClueVisitRecord> clueVisitRecordList = clueVisitRecordDbService.selectClueVisitRecordList(clueId);
                if (clueVisitRecordList != null || clueVisitRecordList.size() > 0) {
                    for (ClueVisitRecord clueVisitRecord : clueVisitRecordList) {
                        clueVisitRecord.setCustomerId(customerId);
                        clueVisitRecordDbService.updateClueVisitRecord(clueVisitRecord);
                    }
                }

                int mergeState = 0;
                //插入联系人表
                List<ClueContact> clueContactList = clueContactDbService.selectClueContactList(clueId);
                if (clueContactList != null || clueContactList.size() > 0) {
                    for (ClueContact clueContact : clueContactList) {
                        CustomerContactPerson customerContactPerson = new CustomerContactPerson();
                        CustomerContactPerson customerContactPersonqc = new CustomerContactPerson();
                        List<CustomerContactPerson> customerContactPersonList = customerDbService.getCustomerIdAndContactName(customerId, clueContact.getContactName(), clueContact.getContactInformation());
                        if (customerContactPersonList.size() != 0) {
                            customerContactPersonqc = customerContactPersonList.get(0);
                        }

                        /*if (!StringUtils.isBlank(customerContactPersonqc.getCustomerContactPersonId())) {
                            customerContactPerson.setMergeState(0); //合并状态-0合并  1没合并
                        } else {
                            customerContactPerson.setMergeState(1); //合并状态-0合并  1没合并
                        }*/
                        customerContactPerson.setCustomerContactPersonId(CommonUtils.getGUID());
                        customerContactPerson.setContactName(clueContact.getContactName());
                        customerContactPerson.setContactInformation(clueContact.getContactInformation());
                        customerContactPerson.setContactPosition(clueContact.getContactJob());
                        customerContactPerson.setFollowUpTimes(0);  //跟进次数
                        customerContactPerson.setIsSeniorExecutive(1);  //是否高管  0: 高管; 1: 非高管'
                        customerContactPerson.setAbolishState(1);  //废止状态
                        customerContactPerson.setContactState(1);  //联系人类型  主联系人-1   从联系人-2',
                        customerContactPerson.setCreatePeopleId(userAccount.getAccountId());
                        customerContactPerson.setCreateTm(new Date());
                        customerContactPerson.setUpdatePeopleId(userAccount.getAccountId());
                        customerContactPerson.setUpdateTm(new Date());
                        customerContactPerson.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
                        customerContactPerson.setCustomerId(customerId);
                        customerPoolDbService.addCustomerContactPerson(customerContactPerson);

                        Contact contact = new Contact();
                        Contact contactqc = new Contact();
                        //客户详情-新增联系人-名字重复问题   联系人管理表  企业联系人
                        List<Contact> contactList = contactDbService.getCustomerIdAndContactNameAndAccountId(customerId, clueContact.getContactName(), clueContact.getContactInformation(), "0", userAccount.getAccountId());
                        if (contactList.size() != 0) {
                            contactqc = contactList.get(0);
                        }

                        /*if (!StringUtils.isBlank(contactqc.getContactId())) {
                            contact.setMergeState(0);  //合并状态-0合并  1没合并
                        } else {
                            contact.setMergeState(1);
                        }*/

                        contact.setContactId(CommonUtils.getGUID());
                        contact.setContactName(clueContact.getContactName());
                        contact.setContactInformation(clueContact.getContactInformation());
                        contact.setContactPosition(clueContact.getContactJob());
                        contact.setFollowUpTimes(0);
                        contact.setCreatePeopleId(userAccount.getAccountId());
                        contact.setCreateTm(new Date());
                        contact.setUpdatePeopleId(userAccount.getAccountId());
                        contact.setUpdateTm(new Date());
                        contact.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
                        contact.setContactState(1); //联系人类型  主联系人-1   从联系人-2
                        contact.setMemberGrade(1); //客户类型 会员客户-1  非会员客户-2'
                        //contact.setMergeState(0); //合并状态-0合并  1没合并
                        contact.setContactNature(0); //联系人性质  0企业联系人  1非企业联系人
                        contact.setAbolishState(1); //废止状态  1启动 2废止
                        contact.setCustomerId(customerId);
                        contact.setAccountId(userAccount.getAccountId());
                        contact.setCompanyId(userAccount.getCompanyId());
                        //新增联系人管理的联系人
                        customerPoolDbService.addContact(contact);
                    }
                }

                //添加到领取记录表
                CustomerReceive customerReceive = new CustomerReceive();
                String customerReceiveId = CommonUtils.getGUID();
                customerReceive.setCustomerReceiveId(customerReceiveId);
                customerReceive.setReceiveTm(new Date());
                customerReceive.setReceiveWay(1); //领取方式：1-领取；2:分配
                customerReceive.setCustomerId(customerId);
                customerReceiveDbservice.insertCustomerReceive(customerReceive);
            }

            clueDbService.updateClueDistribute(clue);

        } else {
            //clueDbService.updateClueDistribute(clue);
            //clue.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.DELETE_CODE.getState()))); //逻辑删除
            return "CF0001";
        }

        return "success";
    }

    /**
     * 客户详情跟进记录
     *
     * @param pageIndex  页码
     * @param pageSize   分页大小
     * @param sortName   排序列名字
     * @param sortOrder  排序规则(asc/desc)
     * @param customerId 客户id
     * @return
     */
    @Override
    public DhPageInfo<ClueFollowVO> clueFollowList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, String customerId) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        StringBuilder order = new StringBuilder();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch (sortName) {
                case "createTm": {
                    order.append("ccf.create_tm ").append(sortOrder);
                }
                break;
                default:
                    break;
            }
        }
        List<ClueFollowVO> list = clueFollowDbService.followVOListByCustomerId(order.toString(), customerId);
        PageInfo<ClueFollowVO> pageInfo = new PageInfo<ClueFollowVO>(list);
        return new DhPageInfo<ClueFollowVO>(pageInfo, list);
    }

    /**
     * 客户详情拜访记录
     *
     * @param pageIndex  页码
     * @param pageSize   分页大小
     * @param sortName   排序列名字
     * @param sortOrder  排序规则(asc/desc)
     * @param customerId 客户id
     * @return
     */
    @Override
    public DhPageInfo<ClueVisitRecord> visitRecordList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, String customerId) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        StringBuilder order = new StringBuilder();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch (sortName) {
                case "createTm": {
                    order.append("create_tm ").append(sortOrder);
                }
                break;
                default:
                    break;
            }
        }
        List<ClueVisitRecord> list = clueVisitRecordDbService.visitRecordList(order.toString(), customerId);
        PageInfo<ClueVisitRecord> pageInfo = new PageInfo<ClueVisitRecord>(list);
        return new DhPageInfo<ClueVisitRecord>(pageInfo, list);
    }

    /**
     * 客户--分配
     *
     * @param distributeUserId ---被分配人员ID
     * @param customerId       ---客户ID
     * @param customerPoolId   ---客户池ID
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Map<String, Object> distributeCustomer(String distributeUserId, String customerId, String customerPoolId) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息
            String accountId = userAccount.getAccountId();
            if (!StringUtils.isBlank(distributeUserId)) {
                SysParameterSetting sysParameterSetting = parameterSettingDbService.selectSystemParameterSetting();
                int maxCount = sysParameterSetting != null ? sysParameterSetting.getMaxCustomerNum() : 0;
                //根据用户id查询我的客户非会员客户数量
                long count = customerDbService.selectNonmemberCustomerCountByAccountId(distributeUserId);
                if (count < maxCount) {
                    Customer customer = customerDbService.selectCustomerById(customerId);
                    Integer memberErrorData = customer.getMemberErrorData();
                    if (memberErrorData == 2) {//客户已锁定
                        result.put("d002", "客户已锁定");
                        return result;
                    }
                    UserAccount distributeUserAccount = userAccountDbService.selectUserAccountByAccountId(distributeUserId);
                    String companyId = Objects.nonNull(distributeUserAccount) ? distributeUserAccount.getCompanyId() : "";
                    customer.setCurrentStatus(Short.parseShort("2"));
                    customer.setAssignedPersonId(distributeUserId);
                    customer.setAccountId(distributeUserId);
                    customer.setUpdateTm(new Date());
                    customer.setUpdatePeopleId(accountId);
                    customer.setReceivePeopleId(null);
                    customer.setOwnerId(distributeUserId); //所有人id
                    customer.setCompanyName(companyId); //所属公司
                    Boolean updateResult = customerDbService.updateCustomerByPrimaryKey(customer);

                    if (updateResult) {
                        //新增客户领取记录
                        insertCustomerReceive(customerId, customerPoolId, accountId, 2);

                        //根据客户ID更新商机所有人ID、分公司ID
                        opportunityDbService.updateOpportunityByCustomerId(customerId, distributeUserId, companyId, accountId, new Date());

                        //根据客户ID更新联系人所有人ID、分公司ID
                        contactDbService.updateContactByCustomerId(customerId, distributeUserId, companyId, accountId, new Date());

                        //修改客户联系人表
                        customerContactPersonDbService.updateCustomerContactPersonByCustomerId(customerId, companyId, accountId, new Date());
                        result.put("d000", "分配成功");
                    }
                } else {
                    result.put("d001", "已分配的客户数达到最大值,不能进行分配");
                }
            }
        } catch (RuntimeException e) {
            throw e;
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Boolean releaseCustomer(String customerId, String releaseReason) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        String accountId = userAccount.getAccountId();
        Customer customer = customerDbService.selectCustomerById(customerId);
        //1.修改客户信息
        customer.setCustomerId(customerId);
        customer.setUpdatePeopleId(accountId);
        customer.setUpdateTm(new Date());
        customer.setCurrentStatus((short) 0);
        customer.setReceivePeopleId(null);
        customer.setAssignedPersonId(null);
        customer.setAccountId(null);
        customer.setOwnerId(null); //所有人id
        customer.setCompanyName(null); //所属公司
        Boolean result = customerDbService.updateCustomerByPrimaryKey(customer);

        if (result) {
            //2.新增客户退回记录
            customerReturnService.insertCustomerReturn(accountId, customerId, "2", releaseReason);

            //3.根据客户ID更新商机所有人ID、分公司ID
            opportunityDbService.updateOpportunityByCustomerId(customerId, "", "", accountId, new Date());

            //4.根据客户ID更新联系人所有人ID、分公司ID
            contactDbService.updateContactByCustomerId(customerId, "", "", accountId, new Date());

            //5.修改客户联系人表
            customerContactPersonDbService.updateCustomerContactPersonByCustomerId(customerId, "", accountId, new Date());
        }

        return true;
    }

    @Override
    public List<Customer> getCustomerListByComp() {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        return customerDbService.getCustomerListByComp(userAccount.getCompanyId());
    }

    /**
     * 客户详情合同信息
     *
     * @param pageIndex  页码
     * @param pageSize   分页大小
     * @param sortName   排序列名字
     * @param sortOrder  排序规则(asc/desc)
     * @param customerId 客户id
     * @return
     */
    @Override
    public DhPageInfo<CustomerContractVO> contractList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, String customerId) {
        Customer customer = customerDbService.selectCustomerById(customerId);
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }



        List<CustomerContractVO> list = customerContractDbService.selectContractByCustomerId(customerId, customer.getAccountId(),userAccount.getAccountId());
        PageInfo<CustomerContractVO> pageInfo = new PageInfo<CustomerContractVO>(list);
        return new DhPageInfo<CustomerContractVO>(pageInfo, list);
    }

    /**
     * 客户详情订单信息
     *
     * @param pageIndex  页码
     * @param pageSize   分页大小
     * @param sortName   排序列名字
     * @param sortOrder  排序规则(asc/desc)
     * @param customerId 客户id
     * @return
     */
    @Override
    public DhPageInfo<CustomerProductOrder> orderList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, String customerId) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        StringBuilder order = new StringBuilder();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch (sortName) {
                case "createTm": {
                    order.append("create_tm ").append(sortOrder);
                }
                break;
                default:
                    break;
            }
        }
        List<CustomerProductOrder> list = customerProductOrderDbService.orderList(order.toString(), customerId, userAccount.getAccountId());
        PageInfo<CustomerProductOrder> pageInfo = new PageInfo<CustomerProductOrder>(list);
        return new DhPageInfo<CustomerProductOrder>(pageInfo, list);
    }

    /**
     * 客户详情产品明细
     *
     * @param pageIndex         页码
     * @param pageSize          分页大小
     * @param sortName          排序列名字
     * @param sortOrder         排序规则(asc/desc)
     * @param customerId        客户id
     * @param productCategories 产品分类 0:非会员;1:会员
     * @return
     */
    @Override
    public DhPageInfo<CustFinanceProductOderVO> finishOrderProductList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, String customerId, String productCategories) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        boolean rs = CommonUtils.isAdmin(userAccount.getUserId());

        //增加删除状态查询条件(0:正常;1:已删除)
        short delState = (short) StatusCodeEnum.NORMAL_CODE.getState();

        StringBuilder order = new StringBuilder();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch (sortName) {
                case "createTm": {
                    order.append("cfop.create_tm ").append(sortOrder);
                }
                break;
                default:
                    break;
            }
        }

        List<CustFinanceProductOderVO> list = finishOrderDBservice.finishOrderProductList(delState, customerId, productCategories, order.toString());
        PageInfo<CustFinanceProductOderVO> pageInfo = new PageInfo<CustFinanceProductOderVO>(list);
        return new DhPageInfo<CustFinanceProductOderVO>(pageInfo, list);
    }

    /**
     * 客户详情产品明细
     *
     * @param pageIndex         页码
     * @param pageSize          分页大小
     * @param sortName          排序列名字
     * @param sortOrder         排序规则(asc/desc)
     * @param customerId        客户id
     * @return
     */
    @Override
    public DhPageInfo<CustFinanceProductOderVO> csdFinishOrderProductList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, String customerId) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        boolean rs = CommonUtils.isAdmin(userAccount.getUserId());

        //增加删除状态查询条件(0:正常;1:已删除)
        short delState = (short) StatusCodeEnum.NORMAL_CODE.getState();

        StringBuilder order = new StringBuilder();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch (sortName) {
                case "createTm": {
                    order.append("cfop.create_tm ").append(sortOrder);
                }
                break;
                default:
                    break;
            }
        }

        List<CustFinanceProductOderVO> list = finishOrderDBservice.csdFinishOrderProductList(delState, customerId, order.toString());
        PageInfo<CustFinanceProductOderVO> pageInfo = new PageInfo<CustFinanceProductOderVO>(list);
        return new DhPageInfo<CustFinanceProductOderVO>(pageInfo, list);
    }


    /**
     * 分页展示移交资料页面的客户信息
     *
     * @param pageIndex      页码
     * @param pageSize       页面大小
     * @param moveCustomerQO 筛选条件
     * @param sortName       排序名称
     * @param sortOrder      排序方式 desc/asc
     * @return
     * @Author renshaorong
     * @Date 2021/4/9
     */
    @Override
    public DhPageInfo<CustomerVO> getCustomerListByUserAccountId(Integer pageIndex, Integer pageSize, MoveCustomerQO moveCustomerQO, String sortName, String sortOrder) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        //增加删除状态查询条件(0:正常;1:已删除)
        moveCustomerQO.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());

        StringBuilder order = new StringBuilder();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch (sortName) {
                case "createTm": {
                    order.append("create_tm ").append(sortOrder);
                }
                break;
                default:
                    break;
            }
        }
        List<CustomerVO> customerList = customerDbService.getCustomerListByUserAccountId(moveCustomerQO, order.toString());
        PageInfo<CustomerVO> pageInfo = new PageInfo<CustomerVO>(customerList);
        return new DhPageInfo<CustomerVO>(pageInfo, customerList);
    }

    /**
     * 批量移动客户给指定用户
     *
     * @param customerList 被选中客户List
     * @return
     * @Author renshaorong
     * @Date 2021/4/9
     */
    @Override
    public String moveSelectedCustomers(List<Customer> customerList) {
        //获取当前登陆用户，存入更新者字段中
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();

        //我的客户最大容量
        SysParameterSetting sysParameterSetting = parameterSettingDbService.selectSystemParameterSetting();
        int maxCount = sysParameterSetting != null ? sysParameterSetting.getMaxCustomerNum() : 0;
        String accountId = userAccount.getAccountId();
        //根据用户id查询我的客户非会员客户数量
        long customerCount = customerDbService.selectNonmemberCustomerCountByAccountId(accountId);
        if (customerCount >= maxCount) {
            //超出我的客户容量
            return "MV0001";
        } else if (customerCount + customerList.size() > maxCount) {
            //要移交的客户数大于可被移交数
            return String.valueOf(maxCount - customerCount);
        }

        //修改客户表
        boolean bool = customerDbService.moveSelectedCustomers(customerList, userAccount.getAccountId());
        // sync ES
        for (Customer customer:customerList){
            Customer vo = customerDbService.selectCustomerById(customer.getCustomerId());
            if(vo !=null){
                syncES(vo,accountId,"系统管理-账号管理-移交资料-更改所有人");
            }

            CustomerReceive customerReceive = new CustomerReceive(CommonUtils.getGUID(),customer.getAccountId(),
                    new Date(),3,vo.getCustomerPoolId(),vo.getCustomerId(),vo.getAccountId());
            //插入领取记录
            customerReceiveDbService.insertCustomerReceive(customerReceive);
        }

        return bool ? ResponseCodeEnum.OK.getResponseCode() : ResponseCodeEnum.ERROR.getResponseCode();

    }

    private void syncES(Customer customer,String accountId,String msg) {

        String token = getToken(accountId,msg);

        Map<String, Object> parMap = transBean2Map(customer);
        parMap.put("authorization",token);
        parMap.put("key",accountId);
        try {
            String result = HttpUtil.post(ESurl+"/cutomer/insertOrUpdate",parMap);
            log.info(result);
        } catch (HttpException e) {
            log.info(msg+"ES同步失败");
        }
    }

    private String getToken(String accountId, String msg) {
        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("accountId", accountId);
        try {
            return HttpUtil.post(ESurl+"/token/initToken",tokenMap);
        } catch (Exception e) {
            log.info(msg+"获取token失败");
        }
        return null;
    }


    /**
     * 对象装换map
     * @param obj
     * @return
     */
    private static Map<String, Object> transBean2Map(Object obj) {
        if (obj == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<>();
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                // 得到property对应的getter方法
                Method getter = property.getReadMethod();
                Object value = getter.invoke(obj);
                map.put(key, value);

            }
        } catch (Exception e) {
            System.out.println("transBean2Map Error " + e);
        }
        return map;
    }


    /**
     * 统计客户
     *
     * @param qo
     * @return
     */
    @Override
    public AnalyseCustomerVO analyseCustomer(AnalyseCustomerQO qo) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        qo.setUserId(userAccount.getAccountId());
        Date date = new Date();
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        String time = f.format(date).replaceAll("-", "");
        qo.setAddDateType(getDateUnit(qo.getAddDateType()).toString());
        qo.setMakeDateType(getDateUnit(qo.getMakeDateType()).toString());
        AnalyseCustomerVO resultVo = new AnalyseCustomerVO();
        AnalyseCustomerVO vo = new AnalyseCustomerVO();
        //resultVo = customerDbService.analyseCustomer(qo);
        if (null == resultVo) {
            resultVo = new AnalyseCustomerVO();
        }
        //查询指定时间范围新客户
        resultVo.setAddCustomerList(customerDbService.selectAnalyseAddCustomer(qo));
        //成交客户数量
        resultVo.setMakeCustomerList(customerDbService.selectMakeCustomerCount(qo));
        //查询新单会员数量
        resultVo.setNewVipList(customerContractDbService.selectNewVipCount(qo));
        //查询续费会员合同
        resultVo.setRenewalVipList(customerContractDbService.selectRenewalVipCount(qo));
        //查询会员成交产品
        resultVo.setVipProductMackCount(customerDbService.selectCustomerVipProductMackCount(qo));
        //查询非会员成交产品
        resultVo.setProductMackCount(customerDbService.selectCustomerProductMackCount(qo));
        //客户总数
        resultVo.setAddCustomerCount(customerDbService.selectCustomerCountByAccountId(userAccount.getAccountId()));
        //客户转换率
        resultVo.setCustomerSwitchRatio(divider(getListSum(resultVo.getMakeCustomerList()) * 100, resultVo.getAddCustomerCount()));
        //转换排名
        resultVo.setCustomerSwitchNum(customerContractDbService.selectCustomerSwitchNum(qo));
        //新增会员
        resultVo.setMakeAddVipCount(customerContractDbService.selectMackAddVipCount(qo));
        //续费会员
        resultVo.setRenewalVip(customerContractDbService.selectRenewalVip(qo));
        //到期会员
        resultVo.setExpireVip(customerDbService.selectExpireVip(qo));
        //会员总数
        resultVo.setMakeVipCount(customerContractDbService.selectMakeVipCount(qo));
        //会员转换率
        resultVo.setVipSwitchRatio(divider(resultVo.getMakeVipCount() * 100, resultVo.getAddCustomerCount()));
        resultVo.setVipOwnNum(customerContractDbService.selectVipOwnNum(qo));
        if ("2".equals(qo.getAddDateType())) {
            qo.setAddDateType("5");
        } else if ("5".equals(qo.getAddDateType())) {
            qo.setAddDateType("7");
        }
        BigDecimal big = new BigDecimal("0");
        if ("5".equals(qo.getAddDateType()) || "7".equals(qo.getAddDateType())) {
            //查询上月会员成交产品
            resultVo.setVipProductMackCompare(customerDbService.selectCustomerVipProductMackCount(qo));
            //查询上月非会员成交产品
            resultVo.setProductMackCompare(customerDbService.selectCustomerProductMackCount(qo));
            //上月成交客户数量
            resultVo.setMakeCustomerCount(customerDbService.dealCustomerCount(qo));
            //上月客户转换率
            resultVo.setCustomerSwitchCompare(divider(resultVo.getMakeCustomerCount() * 100, resultVo.getAddCustomerCount()));
            //计算较上月比例
            //会员成交产品
            big = new BigDecimal(String.valueOf(resultVo.getVipProductMackCompare()));
            resultVo.setVipProductMackCompare(countRatio(resultVo.getVipProductMackCount(), big));
            //非会员成交产品
            big = new BigDecimal(String.valueOf(resultVo.getVipProductMackCompare()));
            resultVo.setProductMackCompare(countRatio(resultVo.getProductMackCount(), big));
            //客户转换率
            resultVo.setCustomerSwitchCompare(resultVo.getVipSwitchRatio() - resultVo.getCustomerSwitchCompare());
        }
        if ("2".equals(qo.getMakeDateType())) {
            qo.setAddDateType("5");
        } else if ("5".equals(qo.getMakeDateType())) {
            qo.setAddDateType("7");
        }
        if ("5".equals(qo.getMakeDateType()) || "7".equals(qo.getMakeDateType())) {
            //新增会员
            resultVo.setMakeAddVipCompare(customerContractDbService.selectMackAddVipCount(qo));
            //续费会员
            resultVo.setRenewalVipCompare(customerContractDbService.selectRenewalVip(qo));
            //到期会员
            resultVo.setExpireVipCompare(customerDbService.selectExpireVip(qo));
            //会员总数
            resultVo.setMakeVipCompare(customerContractDbService.selectMakeVipCount(qo));
            //会员转换率
            resultVo.setVipSwitchCompare(divider(resultVo.getMakeVipCompare() * 100, resultVo.getAddCustomerCount()));
            //计算较上月比例
            //会员转换率
            resultVo.setVipSwitchCompare(resultVo.getVipSwitchRatio() - resultVo.getVipSwitchCompare());
            //新增会员
            resultVo.setMakeAddVipCompare(countRatio(resultVo.getMakeAddVipCount(), resultVo.getMakeAddVipCompare()));
            //续费会员
            resultVo.setRenewalVipCompare(countRatio(resultVo.getRenewalVip(), resultVo.getRenewalVipCompare()));
            //到期会员
            resultVo.setExpireVipCompare(countRatio(resultVo.getExpireVip(), resultVo.getExpireVipCompare()));
        }
        return resultVo;
    }



    /**
     * 统计客户
     *
     * @return
     */
    @Override
    public AnalyseCustomerVO analyseCustomerByPeriod(String startDate, String endDate, boolean isSuperAdmin) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        CustomerAnalysisRequestQo qo = new CustomerAnalysisRequestQo();

        if (!isSuperAdmin) {
            qo.setUserId(userAccount.getAccountId());
        } else {
            qo.setCompanyId(userAccount.getCompanyId());
        }
        qo.setStartDate(startDate);
        qo.setEndDate(endDate);

        AnalyseCustomerVO resultVo = new AnalyseCustomerVO();

        // vipProductMackCount  会员成交
        List<CustomerAnalysisQo> memberTransactionProducts = customerDbService.memberTransactionProducts(qo);
        resultVo.setVipProductMackCount(BigDecimal.valueOf(memberTransactionProducts.stream().mapToDouble(CustomerAnalysisQo::getStatistics).sum()));
        //productMackCount      非会员成交
        List<CustomerAnalysisQo> nonMemberTransactionProducts = customerDbService.nonMemberTransactionProducts(qo);
        resultVo.setProductMackCount(BigDecimal.valueOf(nonMemberTransactionProducts.stream().mapToDouble(CustomerAnalysisQo::getStatistics).sum()));

        //makeAddVipCount       新增会员
        List<CustomerAnalysisQo> newMember = customerDbService.newMember(qo);
        resultVo.setMakeAddVipCount(BigDecimal.valueOf(newMember.stream().mapToDouble(CustomerAnalysisQo::getStatistics).sum()));

        //renewalVip            续费会员
        List<CustomerAnalysisQo> renewMember = customerDbService.renewMember(qo);
        resultVo.setRenewalVip(BigDecimal.valueOf(renewMember.stream().mapToDouble(CustomerAnalysisQo::getStatistics).sum()));

        //expireVip             到期会员
        List<CustomerAnalysisQo> expiredMember = customerDbService.expiredMember(qo);
        resultVo.setExpireVip(BigDecimal.valueOf(expiredMember.stream().mapToDouble(CustomerAnalysisQo::getStatistics).sum()));

        //当月每日续费/新增
        // 新合同
        List<Long> newDealMember = null;
        List<Long> everyDayDealMember = null;
        if (isSuperAdmin) {
            newDealMember = customerDbService.everyDayDealMember(userAccount.getCompanyId(), null, "2");
            everyDayDealMember = customerDbService.everyDayDealMember(userAccount.getCompanyId(), null, "4");

        } else {
            newDealMember = customerDbService.everyDayDealMember(null, userAccount.getAccountId(), "2");
            everyDayDealMember = customerDbService.everyDayDealMember(null, userAccount.getAccountId(), "4");
        }

        resultVo.setNewVipList(newDealMember);
        resultVo.setRenewalVipList(everyDayDealMember);

        return resultVo;
    }



    public Long divider(Long max, Long min) {
        if (max == 0 || min == 0) {
            return Long.valueOf("0");
        }
        return max / min;
    }

    /**
     * 计算本月业绩比较上月业绩比例
     *
     * @param l1 上月业绩
     * @param l2 本月业绩
     * @return
     */
    public BigDecimal countRatio(BigDecimal l1, BigDecimal l2) {
        if (l1.toString().indexOf(".00") != -1) {
            l1 = new BigDecimal("0");
        }
        if (l2.toString().indexOf(".00") != -1) {
            l2 = new BigDecimal("0");
        }
        //两个月都为0
        if (l2.toString().equals(l1.toString()) || new BigDecimal("0").equals(l1) || new BigDecimal("0").equals(l2)
                || new BigDecimal("0.00").equals(l1) || new BigDecimal("0.00").equals(l2)) {
            return new BigDecimal("0");
        }
        //上月为0 本月不为0
        if (!new BigDecimal("0").equals(l2.toString()) && !new BigDecimal("0.00").equals(l2.toString()) &&
                (new BigDecimal("0").toString().equals(l1) || new BigDecimal("0.00").toString().equals(l1))) {
            return l2.setScale(1, BigDecimal.ROUND_HALF_UP);
        }
        BigDecimal big = l1.subtract(l2);
        if (new BigDecimal("0").toString().equals(big.toString()) || new BigDecimal("0.00").toString().equals(big.toString())) {
            return new BigDecimal("0");
        }
        big = big.divide(l1, 1, BigDecimal.ROUND_HALF_UP);
        return big;
    }

    private Long getListSum(List<Long> list) {
        Long re = Long.valueOf(0);
        for (int i = 0; i < list.size(); i++) {
            re += list.get(i);
        }
        return re;
    }

    /**
     * 日期类型(全部/本周/本月/本年度)
     *
     * @param dateType -(all:全部; thisWeek:本周; thisMonth:本月; thisYear:本年；thisToday:今天)
     * @return {@link {java.lang.Integer}}
     * @Author chaifuyou
     * @Date 2021/4/1 16:12
     */
    private Integer getDateUnit(String dateType) {
        Integer dateUnit = 0;
        if (!StringUtils.isBlank(dateType)) {
            if ("thisWeek".equals(dateType)) {
                //本周
                dateUnit = 1;
            }
            if ("topMonth".equals(dateType)) {
                //上月
                dateUnit = 5;
            }
            if ("thisMonth".equals(dateType)) {
                //本月
                dateUnit = 2;
            }
            if ("thisYear".equals(dateType)) {
                //本年
                dateUnit = 3;
            }
            if ("thisToday".equals(dateType)) {
                //今天
                dateUnit = 4;
            }
            if ("thisQuarter".equals(dateType)) {
                //本季度
                dateUnit = 6;
            }
        }
        return dateUnit;
    }


    @Override
    public CustomerVO selectOneCustomer() {
        return customerDbService.selectOneCustomer();
    }

    /**
     * 客户意向分析
     *
     * @param dateType
     */
    @Override
    public AnalyseCustomerRedisVO getAnalyseCustomerIntention(String dateType) {
        Integer dateUnit = getDateUnit(dateType);
        AnalyseCustomerRedisVO redisVO = new AnalyseCustomerRedisVO();
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        Long customerCount = customerDbService.selectCustomerCountByAccountId(userAccount.getAccountId());
        String jsonDate = customerRedisService.getAnalyseCustomerIntention(userAccount.getAccountId());
        if (Objects.nonNull(jsonDate)) {
            JSONObject jsonObject = JSONObject.parseObject(jsonDate);
            redisVO = JSONObject.toJavaObject(jsonObject, AnalyseCustomerRedisVO.class);
        } else {
            redisVO = customerDbService.getAnalyseCustomerIntention(userAccount.getAccountId(), dateUnit);
        }
        if (null == redisVO) {
            return new AnalyseCustomerRedisVO();
        }
        //计算占比（数量* 100 / 客户总量）
        redisVO.setIntentionCustomerRatio(divider(redisVO.getIntentionCustomerCount() * 100, customerCount));
        redisVO.setBudgetCustomerRatio(divider(redisVO.getBudgetCustomerCount() * 100, customerCount));
        redisVO.setFollowCustomerRatio(divider(redisVO.getFollowCustomerCount() * 100, customerCount));
        redisVO.setRivalCustomerRatio(divider(redisVO.getRivalCustomerCount() * 100, customerCount));
        redisVO.setOutCustomerRatio(divider(redisVO.getOutCustomerCount() * 100, customerCount));
        return redisVO;
    }


    /**
     * 新增客户时查重
     *
     * @param
     * @return
     * @author yuanyunfeng
     * @date 2021/4/19 14:42
     */
    @Override
    public List<CustomerRepeatVO> findRepeatByCustomerName(String customerName) {
        return customerDbService.findRepeatCustomerName(customerName);
    }

    /**
     * 首页快速查重
     *
     * @param type         类型：1-按客户名称查重；2-按手机号查重
     * @param isVip        是否会员
     * @param checkContent
     * @return
     * @author yuanyunfeng
     * @date 2021/4/19 14:42
     *
     * @update 任少熔
     * @Author renshaorong
     * @Date 2021/10/19
     * 内训与外训隔离开
     */
    @Override
    public List<CustomerFQRepeatVO> fastQueryRepeat(String type, String isVip, String checkContent) {
        if (checkContent.contains("(") || checkContent.contains(")")) {
            checkContent = checkContent.replace("(", "（").replace(")", "）");
        }
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
//        if("9fb1c999393311eb9e0a00163e08893d".equals(userAccount.getCompanyId())){//测试服务器内训部ID
        if("a5d32daa4c4441a395b521685d7ee4fa".equals(userAccount.getCompanyId())){
            //内训部
            return customerDbService.fastQueryRepeatByNx(type, isVip, checkContent);
        }
        return customerDbService.fastQueryRepeat(type, isVip, checkContent);
    }

    /**
     * 新增个人客户
     *
     * @param customerAddQO -客户参数
     * @param multipartFile -上传文件
     * @return {@link {java.lang.String}}
     * @Author pym
     * @Date 2021/4/19 16:52
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public String addIndividualCustomer(CustomerAddQO customerAddQO, MultipartFile multipartFile) throws FastDFSException {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        String companyId = userAccount.getCompanyId();
        CustomerPool customerPool = null;
        //联系人姓名长度不能大于5个字符
        String customerName = customerAddQO.getCustomerName();
        if (StringUtils.isBlank(customerName) || customerName.length() > 5){
            return "C00006";
        }
        //我的客户最大容量
        SysParameterSetting sysParameterSetting = parameterSettingDbService.selectSystemParameterSetting();
        int maxCount = sysParameterSetting != null ? sysParameterSetting.getMaxCustomerNum() : 0;
        String accountId = userAccount.getAccountId();
        //根据用户id查询我的客户非会员客户数量
        long customerCount = customerDbService.selectNonmemberCustomerCountByAccountId(accountId);
        if (customerCount >= maxCount) {
            //超出我的客户容量
            return "C00005";
        }
        //1、查询客户池容量
        //客户池id
        //String customerPoolId = customerAddQO.getCustomerPoolId();
        //企业对外手机
        String enterpriseExternalPhone = customerAddQO.getEnterpriseExternalPhone();
        //根据客户池id查询客户池信息
        //CustomerPool customerPool = customerPoolDbService.selectCustomerPoolById(customerPoolId);
        //根据公司id查询客户池信息
        if (StringUtils.isNotBlank(companyId)) {
            customerPool = customerPoolDbService.selectCustomerPoolCompanyId(companyId);
        }
        if (customerPool == null) {
            //所属公司对应的全国公有池不存在
            return "C00004";
        }
        //客户池容量
        int capacity = customerPool.getCapacity();
        String customerPoolId = customerPool.getCustomerPoolId();
        customerAddQO.setCustomerPoolId(customerPoolId);
        //查询客户池已经存在的客户数
        long count = customerDbService.selectCustomerCount(customerPoolId);
        if (count < capacity) {
            Boolean isContactRepeat = contactDbService.getContactByContactInformation(enterpriseExternalPhone);
            if (isContactRepeat) {
                //联系人已存在
                return "C00003";
            }
            Boolean isIndividualCustomerRepeat = customerDbService.isIndividualCustomerRepeat(enterpriseExternalPhone);
            if (isIndividualCustomerRepeat) {
                //手机号已存在
                return "C00002";
            }
            FileUpload fileUpload = fileUploadService.uploadFile(multipartFile, false);
            customerAddQO.setUploadId(fileUpload != null ? fileUpload.getUploadId() : "");//上传文件id
            customerAddQO.setCustomerType("1");//个人客户
            customerAddQO.setCurrentStatus(Short.parseShort("1"));//已领取
            Customer customer = getCustomer(customerAddQO);
            customer.setWorkplaceName(customerAddQO.getWorkplaceName());//单位名称
            customer.setContactPerson(customerAddQO.getCustomerName());//联系人
            customer.setContactPersonPhone(enterpriseExternalPhone);//联系人电话
            customerDbService.insertCustomer(customer);

            //sync ES
            syncES(customer,accountId,"新增个人客户");

            Contact contact = getContact(customerAddQO, customer);//联系人管理新增联系人
            //新增个人客户发码
            //contactService.contactSendCode(enterpriseExternalPhone,userAccount.getAccountId(),contact.getContactId(),"0");
            //contact.setIsSendCode(1);
            //contact.setUpdatePeopleId(accountId);
            //contact.setUpdateTm(new Date());
            contactDbService.addContact(contact);
            ContactInformation contactInformation = getContactInformation(customerAddQO, userAccount, customer, contact);//新增联系方式
            contactInformationDbService.addContactInformation(contactInformation);



            //保存成功
            return "C00000";
        } else {
            //超出客户池容量
            return "C00001";
        }
    }

    /**
     * 获取联系方式
     *
     * @param customerAddQO 参数
     * @param userAccount   账号信息
     * @param customer      客户
     * @param contact       联系人
     * @return {@link {com.crm.model.entity.contactManager.ContactInformation}}
     * @Author pym
     * @Date 2021/7/19 9:08
     */
    private ContactInformation getContactInformation(CustomerAddQO customerAddQO, UserAccount userAccount, Customer customer, Contact contact) {
        ContactInformation contactInformation = new ContactInformation();
        contactInformation.setContactInformationId(CommonUtils.getGUID());
        contactInformation.setContactInformation(customerAddQO.getEnterpriseExternalPhone());
        contactInformation.setContactType("单位电话");
        contactInformation.setContactInformationType(0);
        contactInformation.setCreatePeopleId(userAccount.getAccountId());
        contactInformation.setCreateTm(new Date());
        contactInformation.setUpdatePeopleId(userAccount.getAccountId());
        contactInformation.setUpdateTm(new Date());
        contactInformation.setAbolishState(1);
        contactInformation.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        contactInformation.setContactId(contact.getContactId());
        contactInformation.setCustomerId(customer.getCustomerId());
        contactInformation.setDataSource(1);
        contactInformation.setCompanyId(userAccount.getCompanyId());
        return contactInformation;
    }

    /**
     * 获取联系人
     *
     * @param customerAddQO 参数
     * @param customer      客户
     * @return {@link {com.crm.model.entity.contactManager.Contact}}
     * @Author pym
     * @Date 2021/6/11 10:31
     */
    private Contact getContact(CustomerAddQO customerAddQO, Customer customer) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        String accountId = userAccount.getAccountId();
        Contact contact = new Contact();
        contact.setContactId(CommonUtils.getGUID());
        contact.setContactName(customerAddQO.getCustomerName());
        contact.setContactInformation(customerAddQO.getEnterpriseExternalPhone());
        contact.setFollowUpTimes(0);
        contact.setCreatePeopleId(accountId);
        contact.setCreateTm(new Date());
        contact.setUpdatePeopleId(accountId);
        contact.setUpdateTm(new Date());
        contact.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        //contact.setContactState();
        //contact.setMemberGrade();
        //contact.setMergeState(0);
        contact.setContactNature(1);
        contact.setAbolishState(1);
        contact.setCustomerId(customer.getCustomerId());
        contact.setAccountId(accountId);
        contact.setCompanyId(userAccount.getCompanyId());
        return contact;
    }

    /**
     * 恢复被释放的客户
     *
     * @param userId
     * @param customerId
     * @return
     */
    @Override
    public boolean recoverCustomer(String userId, String customerId, String customerReturnId) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        Customer customer = customerDbService.selectCustomerById(customerId);
        if (Objects.isNull(customer) || (!"0".equals(customer.getCurrentStatus().toString()) && (!"".equals(customer.getAccountId()) || Objects.nonNull(customer.getAccountId())))) {
            return false;
        }
        CustomerReceive customerReceive = new CustomerReceive();
        customerReceive.setCustomerReceiveId(CommonUtils.getGUID());
        customerReceive.setReceivePeopleId(userId);
        customerReceive.setReceiveTm(new Date());
        customerReceive.setReceiveWay(2);
        customerReceive.setCustomerPoolFromId(customer.getCustomerPoolId());
        customerReceive.setCustomerId(customerId);
        //插入chs_customer_receive
        customerReceiveDbService.insertCustomerReceive(customerReceive);
        customer.setCurrentStatus(Short.valueOf("2"));//状态被分配
        customer.setAccountId(userId);
        customer.setAssignedPersonId(userId);
        customer.setUpdatePeopleId(userAccount.getAccountId());
        customer.setUpdateTm(new Date());
        //修改客户
        customerDbService.updateCustomerById(customer);
        customerReturnDbService.backCustomerReturn(customerReturnId);
        return true;
    }

    /**
     * 会员客户分析
     *
     * @return
     */
    @Override
    public VipCustomerAnalyseVO vipCustomerAnalyse(Integer type) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        if (CommonUtils.isAdmin(userAccount.getUserId())) {
            userAccount.setCompanyId(null);
        }
        String accountId = userAccount.getAccountId();
        String companyId = userAccount.getCompanyId();
        LocalDate localDate = LocalDate.now();
        String thisMonth = localDate.toString().substring(0, 7);
        Integer topYear = Integer.valueOf(localDate.minusYears(1).toString().substring(0, 4));
        Integer thisYear = Integer.valueOf(localDate.toString().substring(0, 4));

        VipCustomerAnalyseVO resultVo = new VipCustomerAnalyseVO();
        //去年的数据vo
        TopYearVipCustomerAnalyseVO topYearVipCustomerAnalyseVO = new TopYearVipCustomerAnalyseVO();
        //今年的数据vo
        ThisYearVipCustomerAnalyseVO thisYearVipCustomerAnalyseVO = new ThisYearVipCustomerAnalyseVO();
        if (type == null || type == 1) {//去年会员消费占比
            //客户消费总额度
            String customerConsumeCount = customerRedisService.getCustomerConsumeCount(topYear, companyId);
            JSONArray jsonObject = JSONObject.parseArray(customerConsumeCount);
            List<BigDecimal> list = JSONArray.toJavaObject(jsonObject, List.class);
            //会员消费额度
            String vipCustomerConsumeCount = customerRedisService.getVipCustomerBuyRise(companyId, topYear);
            jsonObject = JSONObject.parseArray(vipCustomerConsumeCount);
            List<BigDecimal> vipList = JSONArray.toJavaObject(jsonObject, List.class);
            for (int i = 0; i < list.size(); i++) {
                String vipBuyRiseRatio = "0";
                BigDecimal in1 = vipList.get(i);
                BigDecimal in2 = new BigDecimal(String.valueOf(list.get(i)));
                BigDecimal big1 = new BigDecimal("0");
                BigDecimal big2 = new BigDecimal("0.00");
                if (!in1.equals(big1) && !in1.equals(big2) && !in2.equals(big1) && !in2.equals(big2)) {
                    //vipBuyRiseRatio = (topYearVipCustomerAnalyseVO.getVipBuyRiseRatio().get(i) - (list.get(i))) / list.get(i);
                    if (!"0".equals(in1.subtract(in2).toString()) && !"0.00".equals(in1.subtract(in2).toString())) {
                        vipBuyRiseRatio = (in1.subtract(in2)).divide(in2, 2).toString();
                    } else {
                        vipBuyRiseRatio = "0";
                    }
                }
                if (in2.equals(big1) || in2.equals(big2)) {
                    vipBuyRiseRatio = in1.toString();
                }
                if (vipBuyRiseRatio.indexOf(".") != -1) {
                    vipBuyRiseRatio = vipBuyRiseRatio.substring(0, vipBuyRiseRatio.indexOf("."));
                }
                if (Objects.isNull(vipBuyRiseRatio)) {
                    vipBuyRiseRatio = "0";
                }
                topYearVipCustomerAnalyseVO.getVipBuyRatio().add(Integer.valueOf(vipBuyRiseRatio));
            }
        }
        if (type == null || type == 2) {//今年会员消费占比
            //客户消费总额度
            String customerConsumeCount = customerRedisService.getCustomerConsumeCount(thisYear, companyId);
            JSONArray jsonObject = JSONObject.parseArray(customerConsumeCount);
            List<BigDecimal> list = JSONArray.toJavaObject(jsonObject, List.class);
            if (list.size() < 1) {
                list = new ArrayList<>();
            }
            //当月客户消费额度
            BigDecimal thisMonthBig = customerProductOrderDbService.getThisMonthCustomerConsumeCount(thisMonth, companyId);
            list.add(thisMonthBig);
            //会员消费额度
            String vipCustomerConsumeCount = customerRedisService.getVipCustomerBuyRise(companyId, thisYear);
            jsonObject = JSONObject.parseArray(vipCustomerConsumeCount);
            List<BigDecimal> vipList = JSONArray.toJavaObject(jsonObject, List.class);
            if (vipList.size() < 1) {
                vipList = new ArrayList<>();
            }
            //当月会员客户消费额度
            BigDecimal thisMonthVipBig = customerProductOrderDbService.getThisMonthVipCustomerConsumeCount(thisMonth, companyId);
            vipList.add(thisMonthVipBig);
            for (int i = 0; i < list.size(); i++) {
                String vipBuyRiseRatio = "0";
                BigDecimal in1 = vipList.get(i);
                BigDecimal in2 = new BigDecimal(String.valueOf(list.get(i)));
                BigDecimal big1 = new BigDecimal("0");
                BigDecimal big2 = new BigDecimal("0.00");
                if (!in1.equals(big1) && !in1.equals(big2) && !in2.equals(big1) && !in2.equals(big2)) {
                    //vipBuyRiseRatio = (topYearVipCustomerAnalyseVO.getVipBuyRiseRatio().get(i) - (list.get(i))) / list.get(i);
                    if (!"0".equals(in1.subtract(in2).toString()) && !"0.00".equals(in1.subtract(in2).toString())) {
                        vipBuyRiseRatio = (in1.subtract(in2)).divide(in2, 2).toString();
                    } else {
                        vipBuyRiseRatio = "0";
                    }
                }
                if (in2.equals(big1) || in2.equals(big2)) {
                    vipBuyRiseRatio = in1.toString();
                }
                if (vipBuyRiseRatio.indexOf(".") != -1) {
                    vipBuyRiseRatio = vipBuyRiseRatio.substring(0, vipBuyRiseRatio.indexOf("."));
                }
                if (Objects.isNull(vipBuyRiseRatio)) {
                    vipBuyRiseRatio = "0";
                }
                thisYearVipCustomerAnalyseVO.getVipBuyRatio().add(Integer.valueOf(vipBuyRiseRatio));
            }
        }
        if (type == null || type == 3) {//去年会员复购率
            //会员总数
            Integer sutomerCount = customerProductOrderDbService.selectCustomerCount(companyId);
            //续费会员list
            String str = customerRedisService.getRenewVipCustomerCount(topYear, companyId);
            JSONArray jsonObject = JSONObject.parseArray(str);
            List<Integer> list = JSONArray.toJavaObject(jsonObject, List.class);
            for (int i = 0; i < list.size(); i++) {
                Integer vipHoldRatio = 0;
                if (list.get(i) != 0) {
                    vipHoldRatio = list.get(i) / sutomerCount;
                }
                topYearVipCustomerAnalyseVO.getVipAgainBuyRatio().add(vipHoldRatio);
            }
        }
        if (type == null || type == 4) {//今年会员复购率
            //会员总数
            Integer sutomerCount = customerProductOrderDbService.selectCustomerCount(companyId);
            //续费会员list
            String str = customerRedisService.getRenewVipCustomerCount(thisYear, companyId);
            JSONArray jsonObject = JSONObject.parseArray(str);
            List<Integer> list = JSONArray.toJavaObject(jsonObject, List.class);
            if (list.size() < 1) {
                list = new ArrayList<>();
            }
            //当月续费会员数量
            Integer thisMonthRenewVip = customerProductOrderDbService.selectThisMonthRenewVip(thisMonth, companyId);
            list.add(thisMonthRenewVip);
            for (int i = 0; i < list.size(); i++) {
                Integer vipHoldRatio = 0;
                if (list.get(i) != 0) {
                    vipHoldRatio = list.get(i) / sutomerCount;
                }
                thisYearVipCustomerAnalyseVO.getVipAgainBuyRatio().add(vipHoldRatio);
            }
        }
        if (type == null || type == 5) {//去年会员保持率

            //topYearVipCustomerAnalyseVO.setVipHoldRatio(customerDbService.getAnalyseVipHoldRatio(topYear,companyId));
            String str = customerRedisService.getVipCustomerCount(topYear, companyId);
            JSONArray jsonObject = JSONObject.parseArray(str);
            topYearVipCustomerAnalyseVO.setVipHoldRatio(JSONArray.toJavaObject(jsonObject, List.class));
            // List<Integer> list = customerDbService.getCustomerCount(topYear,companyId);
            str = customerRedisService.getOutVipAgainBuyRatio(companyId, topYear);
            jsonObject = JSONObject.parseArray(str);
            List<Integer> list = JSONArray.toJavaObject(jsonObject, List.class);
            for (int i = 0; i < topYearVipCustomerAnalyseVO.getVipHoldRatio().size(); i++) {
                Integer vipHoldRatio = 0;
                if (topYearVipCustomerAnalyseVO.getVipHoldRatio().get(i) != 0 && list.get(i) != 0) {
                    vipHoldRatio = 100 - (list.get(i) / topYearVipCustomerAnalyseVO.getVipHoldRatio().get(i));
                }
                if (list.get(i) == 0) {
                    vipHoldRatio = 100;
                }
                topYearVipCustomerAnalyseVO.getVipHoldRatio().set(i, vipHoldRatio);
            }
        }
        if (type == null || type == 6) {//今年会员保持率
            //流失客户
            String str = customerRedisService.getOutVipAgainBuyRatio(companyId, thisYear);
            JSONArray jsonObject = JSONObject.parseArray(str);
            List<Integer> list = JSONArray.toJavaObject(jsonObject, List.class);
            if (list.size() < 1) {
                list = new ArrayList<>();
            }
            //本月流失数量
            Integer outVip = customerDbService.selectThisMonthOutVip(thisMonth, companyId);
            list.add(outVip);
            // thisYearVipCustomerAnalyseVO.setVipHoldRatio(customerDbService.getAnalyseVipHoldRatio(thisYear,companyId));
            //会员数量
            str = customerRedisService.getVipCustomerCount(thisYear, companyId);
            jsonObject = JSONObject.parseArray(str);
            thisYearVipCustomerAnalyseVO.setVipHoldRatio(JSONArray.toJavaObject(jsonObject, List.class));
            if (thisYearVipCustomerAnalyseVO.getVipHoldRatio().size() < 1) {
                thisYearVipCustomerAnalyseVO.setVipHoldRatio(new ArrayList<>());
            }
            //当月会员数量
            Integer thisMonthVipCount = customerDbService.selectThisMonthVipCount(thisMonth, companyId);
            thisYearVipCustomerAnalyseVO.getVipHoldRatio().add(thisMonthVipCount);
            for (int i = 0; i < thisYearVipCustomerAnalyseVO.getVipHoldRatio().size(); i++) {
                Integer vipHoldRatio = thisYearVipCustomerAnalyseVO.getVipHoldRatio().get(i);
                if (thisYearVipCustomerAnalyseVO.getVipHoldRatio().get(i) != 0 && list.get(i) != 0) {
                    vipHoldRatio = 100 - (list.get(i) / thisYearVipCustomerAnalyseVO.getVipHoldRatio().get(i)  /**100*/);
                }
                if (list.get(i) == 0) {
                    vipHoldRatio = 100;
                }
                if (thisYearVipCustomerAnalyseVO.getVipHoldRatio().get(i) == 0) {
                    vipHoldRatio = 0;
                }
                thisYearVipCustomerAnalyseVO.getVipHoldRatio().set(i, vipHoldRatio);
            }
        }
        if (type == null || type == 7) {
            //去年会员流失率
            //topYearVipCustomerAnalyseVO.setVipOutRatio(customerDbService.getAnalyseVipOutRatio(topYear,companyId));
            String str = customerRedisService.getVipCustomerCount(topYear, companyId);
            JSONArray jsonObject = JSONObject.parseArray(str);
            topYearVipCustomerAnalyseVO.setVipOutRatio(JSONArray.toJavaObject(jsonObject, List.class));

            str = customerRedisService.getOutVipAgainBuyRatio(companyId, thisYear);
            jsonObject = JSONObject.parseArray(str);
            List<Integer> list = JSONArray.toJavaObject(jsonObject, List.class);
            for (int i = 0; i < list.size(); i++) {
                Integer vipHoldRatio = topYearVipCustomerAnalyseVO.getVipOutRatio().get(i);
                if (topYearVipCustomerAnalyseVO.getVipOutRatio().get(i) != 0 && list.get(i) != 0) {
                    vipHoldRatio = list.get(i) / topYearVipCustomerAnalyseVO.getVipOutRatio().get(i);  /**100*/
                }
                if (list.get(i) == 0) {
                    vipHoldRatio = 100;
                }
                if (topYearVipCustomerAnalyseVO.getVipOutRatio().get(i) == 0) {
                    vipHoldRatio = 0;
                }
                topYearVipCustomerAnalyseVO.getVipOutRatio().set(i, vipHoldRatio);
            }
        }
        if (type == null || type == 8) {
            //今年会员流失率
            //thisYearVipCustomerAnalyseVO.setVipOutRatio(customerDbService.getAnalyseVipOutRatio(thisYear,companyId));
            String str = customerRedisService.getVipCustomerCount(thisYear, companyId);
            JSONArray jsonObject = JSONObject.parseArray(str);
            thisYearVipCustomerAnalyseVO.setVipOutRatio(JSONArray.toJavaObject(jsonObject, List.class));
            if (thisYearVipCustomerAnalyseVO.getVipOutRatio().size() < 1) {
                thisYearVipCustomerAnalyseVO.setVipOutRatio(new ArrayList<>());
            }
            //当月会员数量
            Integer thisMonthVipCount = customerDbService.selectThisMonthVipCount(thisMonth, companyId);
            thisYearVipCustomerAnalyseVO.getVipOutRatio().add(thisMonthVipCount);
            //流失
            str = customerRedisService.getOutVipAgainBuyRatio(companyId, thisYear);
            jsonObject = JSONObject.parseArray(str);
            List<Integer> list = JSONArray.toJavaObject(jsonObject, List.class);
            if (list.size() < 1) {
                list = new ArrayList<>();
            }
            //本月流失数量
            Integer outVip = customerDbService.selectThisMonthOutVip(thisMonth, companyId);
            list.add(outVip);
            for (int i = 0; i < list.size(); i++) {
                Integer vipHoldRatio = thisYearVipCustomerAnalyseVO.getVipOutRatio().get(i);
                if (thisYearVipCustomerAnalyseVO.getVipOutRatio().get(i) != 0 && list.get(i) != 0) {
                    vipHoldRatio = list.get(i) / thisYearVipCustomerAnalyseVO.getVipOutRatio().get(i);  /**100*/
                }
                if (list.get(i) == 0) {
                    vipHoldRatio = 100;
                }
                if (thisYearVipCustomerAnalyseVO.getVipOutRatio().get(i) == 0) {
                    vipHoldRatio = 0;
                }
                thisYearVipCustomerAnalyseVO.getVipOutRatio().set(i, vipHoldRatio);
            }
        }
        if (type == null || type == 9) {
            //去年会员交易增长率
            //List<BigDecimal> bigList = customerProductOrderDbService.getAnalyseVipBuyRiseRatio(topYear,companyId);
            String str = customerRedisService.getVipCustomerBuyRise(companyId, topYear);
            JSONArray jsonObject = JSONObject.parseArray(str);
            List<BigDecimal> bigList = jsonObject.toJavaObject(jsonObject, List.class);
            ;
            //List<BigDecimal> list = customerProductOrderDbService.getAnalyseVipBuyRiseRatio(topYear-1,companyId);
            str = customerRedisService.getVipCustomerBuyRise(companyId, topYear - 1);
            jsonObject = JSONObject.parseArray(str);
            List<BigDecimal> list = JSONArray.toJavaObject(jsonObject, List.class);
            for (int i = 0; i < bigList.size(); i++) {
                String vipBuyRiseRatio = "0";
                BigDecimal in1 = bigList.get(i);
                BigDecimal in2 = list.get(i);
                BigDecimal big1 = new BigDecimal("0");
                BigDecimal big2 = new BigDecimal("0.00");
                if (!in1.equals(big1) && !in1.equals(big2) && !in2.equals(big1) && !in2.equals(big2)) {
                    //vipBuyRiseRatio = (topYearVipCustomerAnalyseVO.getVipBuyRiseRatio().get(i) - (list.get(i))) / list.get(i);
                    if (!"0".equals(in1.subtract(in2).toString()) && !"0.00".equals(in1.subtract(in2).toString())) {
                        vipBuyRiseRatio = (in1.subtract(in2)).divide(in2, 2).toString();
                    } else {
                        vipBuyRiseRatio = "0";
                    }
                }
                if (in2.equals(big1) || in2.equals(big2)) {
                    vipBuyRiseRatio = in1.toString();
                }
                if (vipBuyRiseRatio.indexOf(".") != -1) {
                    vipBuyRiseRatio = vipBuyRiseRatio.substring(0, vipBuyRiseRatio.indexOf("."));
                }
                if (Objects.isNull(vipBuyRiseRatio)) {
                    vipBuyRiseRatio = "0";
                }
                topYearVipCustomerAnalyseVO.getVipBuyRiseRatio().add(Long.valueOf(vipBuyRiseRatio));
            }
        }
        if (type == null || type == 10) {
            //今年会员交易增长率
            //List<BigDecimal> bigList = customerProductOrderDbService.getAnalyseVipBuyRiseRatio(thisYear,companyId);
            String str = customerRedisService.getVipCustomerBuyRise(companyId, thisYear);
            JSONArray jsonObject = JSONObject.parseArray(str);
            List<BigDecimal> bigList = jsonObject.toJavaObject(jsonObject, List.class);
            BigDecimal thisMonthBig = customerProductOrderDbService.selectThisMonthBigByCompanyId(companyId, thisMonth);
            bigList.add(thisMonthBig);
            //List<BigDecimal> list = customerProductOrderDbService.getAnalyseVipBuyRiseRatio(thisYear-1,companyId);
            str = customerRedisService.getVipCustomerBuyRise(companyId, thisYear - 1);
            jsonObject = JSONObject.parseArray(str);
            List<BigDecimal> list = JSONArray.toJavaObject(jsonObject, List.class);
            for (int i = 0; i < bigList.size(); i++) {
                String vipBuyRiseRatio = "0";
                BigDecimal in1 = bigList.get(i);
                BigDecimal in2 = list.get(i);
                BigDecimal big1 = new BigDecimal("0");
                BigDecimal big2 = new BigDecimal("0.00");
                if (!in1.equals(big1) && !in1.equals(big2) && !in2.equals(big1) && !in2.equals(big2)) {
                    vipBuyRiseRatio = (in1.subtract(in2)).divide(in2, 2).toString();
                }
                if (in2.equals(big1) || in2.equals(big2)) {
                    vipBuyRiseRatio = in1.toString();
                }
                if (vipBuyRiseRatio.indexOf(".") != -1) {
                    vipBuyRiseRatio = vipBuyRiseRatio.substring(0, vipBuyRiseRatio.indexOf("."));
                }
                if (Objects.isNull(vipBuyRiseRatio)) {
                    vipBuyRiseRatio = "0";
                }
                thisYearVipCustomerAnalyseVO.getVipBuyRiseRatio().add(Long.valueOf(vipBuyRiseRatio));
            }
        }
        resultVo.setThisYearVipCustomerAnalyse(thisYearVipCustomerAnalyseVO);
        resultVo.setTopYearVipCustomerAnalyse(topYearVipCustomerAnalyseVO);
        return resultVo;
    }


    /**
     * 会员客户数量统计
     *
     * @return
     */
    @Override
    public VipCustomerAnalyseVO getVipCustomerCount() {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        if (CommonUtils.isAdmin(userAccount.getUserId())) {
            userAccount.setCompanyId(null);
        }
        String companyId = userAccount.getCompanyId();
        LocalDate startDate = LocalDate.now().minusDays(30);
        return customerDbService.getVipCustomerCount(startDate, companyId);
    }

    /**
     * 会员客户列表
     *
     * @param pageIndex
     * @param pageSize
     * @param membershipLevel
     * @param sortName
     * @param sortOrder
     * @return
     */
    @Override
    public DhPageInfo<VipCustomerListVO> selectVipCustomerList(Integer pageIndex, Integer pageSize, Integer membershipLevel, String sortName, String sortOrder) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        if (CommonUtils.isAdmin(userAccount.getUserId())) {
            userAccount.setCompanyId(null);
        }
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        StringBuilder order = new StringBuilder();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch (sortName) {
                case "membershipExpirationTm": {
                    order.append("membership_expiration_tm ").append(sortOrder);
                }
                break;
                case "membershipLevel": {
                    order.append("membership_level ").append(sortOrder);
                }
                break;
                case "membershipStartTm": {
                    order.append("membership_start_tm ").append(sortOrder);
                }
                break;
                default:
                    break;
            }
        }
        List<VipCustomerListVO> customerList = customerDbService.selectVipCustomerList(membershipLevel, order.toString(), userAccount.getCompanyId());
        PageInfo<VipCustomerListVO> pageInfo = new PageInfo<VipCustomerListVO>(customerList);
        return new DhPageInfo<VipCustomerListVO>(pageInfo, customerList);
    }

    /**
     * 联系人列表跳转客户详情-查询是不是自己的客户
     *
     * @param customerId 客户id
     * @return
     */
    @Override
    public boolean selectCustomerSelf(String customerId) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        return customerDbService.selectCustomerSelf(customerId, userAccount.getAccountId());
    }

    /**
     * 新增商机-客户名称精准匹配
     *
     * @param customerName 客户名称
     * @return
     */
    @Override
    public boolean selectCustomerNameReg(String customerName) {
        return customerDbService.selectCustomerNameReg(customerName);
    }

    /**
     * 客户详情-修改客户评分
     *
     * @param customerId     客户id
     * @param customerRating 客户评分
     * @return
     */
    @Override
    public Boolean updateCustomerRating(String customerId, String customerRating) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        Customer customer = customerPoolDbService.getCustomer(customerId);
        if (customer == null) {
            return false;
        }
        if (StringUtils.isBlank(customer.getCustomerRating())) {
            customer.setCustomerRating("");
        }

        if (!customerRating.equals(customer.getCustomerRating())) {
            ModificationRecord modificationRecord = new ModificationRecord();
            String modificationRecordId = CommonUtils.getGUID();
            modificationRecord.setModificationRecordId(modificationRecordId);
            modificationRecord.setModificationName("客户评分");
            if (StringUtils.isBlank(customer.getCustomerRating())) {
                modificationRecord.setBeforeModification("");
            } else {
                modificationRecord.setBeforeModification(customer.getCustomerRating()); //修改前
            }
            if (StringUtils.isBlank(customerRating)) {
                modificationRecord.setAfterModification("");
            } else {
                modificationRecord.setAfterModification(customerRating); //修改后
            }
            modificationRecord.setVerifyStatus(3);
            modificationRecord.setCreatePeopleId(userAccount.getAccountId());
            modificationRecord.setCreateTm(new Date());
            modificationRecord.setUpdatePeopleId(userAccount.getAccountId());
            modificationRecord.setUpdateTm(new Date());
            modificationRecord.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
            modificationRecord.setCustomerId(customer.getCustomerId());
            boolean bs = customerPoolDbService.addModificationRecord(modificationRecord);
        }


        customer.setCustomerRating(customerRating);
        customer.setUpdatePeopleId(userAccount.getAccountId());
        customer.setUpdateTm(new Date());
        customer.setAccountId(userAccount.getAccountId());
        boolean result = customerPoolDbService.updateCustomer(customer);
        syncES(customer,userAccount.getAccountId(),"客户详情-客户评分");
        return result;
    }

    /**
     * 客户管理 - 单品客户 - 新增单品客户列表
     *
     * @param pageIndex    页码
     * @param pageSize     分页大小
     * @param customerName 客户名称
     * @param sortName     排序列名字
     * @param sortOrder    排序规则(asc/desc)
     * @return {@link {com.crm.common.model.DhPageInfo<com.crm.model.vo.customerManager.CustomerVO>}}
     * @Author pym
     * @Date 2021/4/30 10:54
     */
    @Override
    public DhPageInfo<CustomerVO> selectSingleProductCustomerList(Integer pageIndex, Integer pageSize, String customerName, String sortName, String sortOrder) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        String accountId = userAccount.getAccountId();
        String companyId = userAccount.getCompanyId();
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        List<CustomerVO> customerList = customerDbService.selectSingleProductCustomerList(customerName, accountId, companyId);
        PageInfo<CustomerVO> pageInfo = new PageInfo<CustomerVO>(customerList);
        return new DhPageInfo<CustomerVO>(pageInfo, customerList);
    }

    /**
     * 根据客户Id查询客户信息
     *
     * @param customerId
     * @return
     */
    @Override
    public Customer selectCustomerById(String customerId) {
        Customer customer = customerDbService.selectCustomerById(customerId);
        return customer;
    }

    /**
     * qo精确查询客户
     *
     * @param pageIndex
     * @param pageSize
     * @param customerQO
     * @param sortName
     * @param sortOrder
     * @return
     */
    @Override
    public DhPageInfo<CustomerVO> selectCustomerPreciseSearch(Integer pageIndex, Integer pageSize, CustomerQO customerQO, String sortName, String sortOrder) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        //增加删除状态查询条件(0:正常;1:已删除)
        customerQO.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());
        List<CustomerVO> customerList = customerDbService.selectCustomerPreciseSearch(customerQO);
        PageInfo<CustomerVO> pageInfo = new PageInfo<CustomerVO>(customerList);
        return new DhPageInfo<CustomerVO>(pageInfo, customerList);
    }

    /**
     * 修改客户编码
     *
     * @param customerId
     */
    @Override
    public void updateCustomerNumber(String customerId) {
        Customer customer = customerDbService.selectCustomerById(customerId);
        customer.setCustomerNumber(createCustomerNumber());
        customerDbService.updateCustomerById(customer);
    }

    /**
     * 生成客户编号
     *
     * @return
     */
    @Override
    public String createCustomerNumber() {
        String datetime = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String newCustomerNumber = datetime + "00001";
        String maxCustomerNumber = customerDbService.selectMaxCustomerNumber(datetime);
        if (Objects.nonNull(maxCustomerNumber)) {
            if (maxCustomerNumber.length() < 8) {
                maxCustomerNumber = customerDbService.selectMaxCustomerNumber(datetime);
                if (Objects.isNull(maxCustomerNumber)) {
                    return newCustomerNumber;
                }
            }
            if (datetime.equals(maxCustomerNumber.substring(0, 8))) {
                newCustomerNumber = datetime + String.format("%05d", Integer.parseInt(maxCustomerNumber.substring(8)) + 1);
            }
        }
        return newCustomerNumber;
    }


    /**
     * @Description: 根据客户名称检索数据
     * @Param: [customerName]
     * @Return: java.util.List<com.crm.model.entity.customerManager.Customer>
     * @Author: lixq-f
     * @Date: 2021/5/13
     **/
    @Override
    public List<DataSearchResultVO> selectDataByCustomerName(String customerName) {
        return customerDbService.selectDataByCustomerName(customerName);
    }

    /**
     * 客户管理-客户详情-会员产品-详细信息
     *
     * @param customerId            客户Id
     * @param memberProductId       会员产品id
     * @param finishOrderProductNum 产品号
     * @param orderId               订单id
     * @param memberProductCode     产品编码
     * @param bs                    0会员 1非会员
     * @return
     */
    @Override
    public CustomerProductDetailMemberCardVO selectCustomerProductDetail(String customerId, String memberProductId, String finishOrderProductNum, String orderId, String memberProductCode, String bs) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        CustomerProductDetailMemberCardVO customerProductDetailMemberCardVO = new CustomerProductDetailMemberCardVO();

        CustomerProductOrder customerProductOrder = customerProductOrderDbService.selectCustomerProductOrderById(orderId);
        //会员卡
        List<CustomerProductDetailMemberCard> cardList = customerDbService.getMemberCardByOrderIdAndCph(orderId, finishOrderProductNum);
        if (cardList != null && cardList.size() > 0) {
            customerProductDetailMemberCardVO.setCustomerProductDetailMemberCard(cardList);
        }

        //税法直通车
        List<CustomerProductDetailThroughTrainTax> taxList = customerDbService.getThroughTrainTaxByOrderIdAndCph(orderId, finishOrderProductNum);
        if (taxList != null && taxList.size() > 0) {
            customerProductDetailMemberCardVO.setTaxList(taxList);
        }

        boolean flag = false;
        //兑换码
        SimpleDateFormat sdf  =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //创建日期转换对象：年 月 日
        String date = "2021-08-01 00:00:00"; //假设 设定日期是  2018-11-11
        try {
            Date dateD = sdf.parse(date); //将字符串转换为 date 类型  Debug：Sun Nov 11 00:00:00 CST 2018
            flag = customerProductOrder.getCreateTm().getTime() < dateD.getTime();
        } catch (ParseException e1) {
            e1.printStackTrace();
        }
        if(flag) {
            List<CustomerProductDetailExchangeCode> codeList = customerDbService.getExchangeCodeByOrderIdAndCph(orderId, "1");
            if (codeList != null && codeList.size() > 0) {
                customerProductDetailMemberCardVO.setCodeList(codeList);
            }
        }else{
            List<CustomerProductDetailExchangeCode> codeList = customerDbService.getExchangeCodeByOrderIdAndCph(orderId, finishOrderProductNum);
            if (codeList != null && codeList.size() > 0) {
                customerProductDetailMemberCardVO.setCodeList(codeList);
            }
        }



        //云顾问卡
        List<CustomerProductDetailYun> yunList = customerDbService.getYunByOrderIdAndCph(orderId, finishOrderProductNum);
        if (yunList != null && yunList.size() > 0) {
            customerProductDetailMemberCardVO.setYunList(yunList);
        }

        //充值卡
        List<CustomerProductDetailRechargeCode> rechargeCodeList = customerDbService.getRechargeCodeByOrderIdAndCph(orderId, finishOrderProductNum);
        if (rechargeCodeList != null && rechargeCodeList.size() > 0) {
            customerProductDetailMemberCardVO.setRechargeCodeList(rechargeCodeList);
        }

        //优惠劵
        List<CustomerProductDetailCoupon> couponsList = customerDbService.getCouponsByOrderIdAndCph(orderId, finishOrderProductNum);
        if (couponsList != null && couponsList.size() > 0) {
            customerProductDetailMemberCardVO.setCouponsList(couponsList);
        }

        List<CourseVO> list = customerDbService.selectCustomerProductDetail(customerId, finishOrderProductNum);
        //会员产品显示
        if ("0".equals(bs)) {
            if (list.size() == 0) {
                List<CustomerProductDetailVO> produsctDetai = customerMemberProductService.queryCustomerProductDetailInfo(memberProductId);
                if (produsctDetai.size() != 0) {
                    for (int i = 0; i < produsctDetai.size(); i++) {
                        CustomerProductDetailVO customerProductDetailVO = produsctDetai.get(i);
                        if (produsctDetai.get(i).getCourseSub() != null) {
                            for (int j = 0; j < produsctDetai.get(i).getCourseSub().size(); j++) {
                                CourseSubVO courseSubVO = produsctDetai.get(i).getCourseSub().get(j);
                                List<CustomerMemberProductCourseVO> courseVOS = memberProductCourseService.selectMemberProductCourseByRelationId(courseSubVO.getRelationId());
                                if (courseVOS != null && courseVOS.size() != 0) {
                                    String productCode = String.valueOf(new Date().getTime()) + 0 + i;
                                    for (int k = 0; k < courseVOS.size(); k++) {
                                        CustomerProductDetail customerProductDetail = zzCustomerProductDetail(customerProductDetailVO, finishOrderProductNum, userAccount.getAccountId(), customerId);

                                        customerProductDetail.setCourseNum(productCode);  //0课程 1课程下产品
                                        customerProductDetail.setServiceType(courseSubVO.getServiceType());
                                        customerProductDetail.setCourseTypeId(courseSubVO.getCourseTypeId());  //课程类型id
                                        customerProductDetail.setCourseSubcategoryId(courseSubVO.getCourseSubcategoryId());//课程小类id
                                        customerProductDetail.setServiceCount(String.valueOf(courseSubVO.getServiceCount()));

                                        CustomerMemberProductCourseVO customerMemberProductCourseVO = courseVOS.get(k);
                                        customerProductDetail.setCustomerProductId(String.valueOf(new Date().getTime()) + 1 + i);  //0课程 1课程下产品
                                        customerProductDetail.setCustomerProductName(customerMemberProductCourseVO.getCustomerProductName());
                                        customerProductDetail.setServiceClassification(customerMemberProductCourseVO.getServiceClassification());
                                        customerProductDetail.setCourseCount(customerMemberProductCourseVO.getCourseCount());
                                        customerProductDetail.setExchangeMethod(customerMemberProductCourseVO.getExchangeMethod());

                                        customerDbService.insertCustomerProductDetail(customerProductDetail);
                                    }
                                } else {
                                    CustomerProductDetail customerProductDetail = zzCustomerProductDetail(customerProductDetailVO, finishOrderProductNum, userAccount.getAccountId(), customerId);

                                    customerProductDetail.setCourseNum(String.valueOf(new Date().getTime()) + 0 + i);  //0课程 1课程下产品
                                    customerProductDetail.setServiceType(courseSubVO.getServiceType());
                                    customerProductDetail.setCourseTypeId(courseSubVO.getCourseTypeId());  //课程类型id
                                    customerProductDetail.setCourseSubcategoryId(courseSubVO.getCourseSubcategoryId());//课程小类id
                                    customerProductDetail.setServiceCount(String.valueOf(courseSubVO.getServiceCount()));
                                    customerDbService.insertCustomerProductDetail(customerProductDetail);
                                }
                            }
                        } else {
                            CustomerProductDetail customerProductDetail = zzCustomerProductDetail(customerProductDetailVO, finishOrderProductNum, userAccount.getAccountId(), customerId);
                            customerDbService.insertCustomerProductDetail(customerProductDetail);
                        }

                    }
                }

                list = customerDbService.selectCustomerProductDetail(customerId, finishOrderProductNum);
                customerProductDetailMemberCardVO.setList(list);
            }


        }

        return customerProductDetailMemberCardVO;

    }

    /**
     * 客户管理-客户详情-会员产品-课程-产品信息
     *
     * @param customerId 客户Id
     * @param courseNum  课程标号
     * @return
     */
    @Override
    public List<CustomerProductVO> selectCustomerProduct(String customerId, String courseNum) {
        return customerDbService.selectCustomerProduct(customerId, courseNum);
    }

    /**
     * 我的客户-查询客户里面有的行业
     *
     * @param bs   0管理端 1用户端
     * @param type industry行业 province地区
     * @return
     */
    @Override
    public List<IndustryAreaVO> selectIndustry(String bs, String type) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        boolean rs = CommonUtils.isAdmin(userAccount.getUserId());
        String name = null;
        //number  0超管 1普通管理员  2普通用户
        Integer number = 0;
        if ("0".equals(bs)) {
            if (rs) {
                number = 0;
            } else {
                //普通管理员
                number = 1;
                name = userAccount.getCompanyId();
            }
        } else {
            //普通用户
            number = 2;
            name = userAccount.getAccountId();
        }
        if ("industry".equals(type)) {
            return customerDbService.selectIndustry(name, number);
        } else {
            return customerDbService.selectProvince(name, number);
        }
    }

    /**
     * 我的客户-查询客户里面的热门标签
     *
     * @param bs 0管理端 1用户端
     * @return
     */
    @Override
    public List<TagVO> selectTag(String bs) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        boolean rs = CommonUtils.isAdmin(userAccount.getUserId());
        String name = null;
        //number  0超管 1普通管理员  2普通用户
        Integer number = 0;
        if ("0".equals(bs)) {
            if (rs) {
                number = 0;
            } else {
                //普通管理员
                number = 1;
                name = userAccount.getCompanyId();
            }
        } else {
            //普通用户
            number = 2;
            name = userAccount.getAccountId();
        }
        return customerDbService.selectTag(name, number);
    }

    /**
     * 查询客户里面的跟进标签
     *
     * @param bs
     * @return
     */
    @Override
    public List<TagVO> selectFollowTag(String bs) {
        ClueFollowTagVO followTagVO = new ClueFollowTagVO();
        String jsonDate = customerRedisService.selectFollowTag();
        List<TagVO> resultList = new ArrayList<>();
        if (Objects.nonNull(jsonDate)) {
            List<String> strList = Arrays.asList(jsonDate.split(","));
            for (int i = 0; i < strList.size(); i++) {
                TagVO tagVO = new TagVO();
                tagVO.setTag(strList.get(i));
                resultList.add(tagVO);
            }
        } else { //redis没查到去数据库查并插入redis
            UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
            List<String> tagList = customerDbService.selectCustomerFollowTag(userAccount.getAccountId());
            if (tagList.size() > 0) {
                String tabStr = "";
                for (int i = 0; i < tagList.size(); i++) {
                    TagVO tagVO = new TagVO();
                    tagVO.setTag(tagList.get(i));
                    resultList.add(tagVO);
                    tabStr += (tagList.get(i) + ",");
                }
                customerRedisService.addFollowTagsToRedis(tabStr);
                return resultList;
            }
        }
        return resultList;
    }

    /**
     * 联系人-新增个人联系人--查询同一用户下的联系方式不能一样
     *
     * @param contactName        客户名称
     * @param contactInformation 联系方式
     * @param contactNature      联系人性质  0企业联系人  1非企业联系人
     * @return
     */
    @Override
    public Customer getCustomerNameAndPhone(String contactName, String contactInformation, String contactNature) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        return customerDbService.getCustomerNameAndPhone(contactName, contactInformation, contactNature, userAccount.getAccountId());
    }

    /**
     * 客户-客户订单完成的会员产品会员卡
     *
     * @param customerProductDetailMemberCard 客户订单完成的会员产品会员卡实体
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public String addCustomerProductDetailMemberCard(CustomerProductDetailMemberCard customerProductDetailMemberCard) {
        Map<String, Object> map = new HashMap<>();
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        String customerProductDetailMemberCardId = CommonUtils.getGUID();
        customerProductDetailMemberCard.setCustomerProductDetailMemberCardId(customerProductDetailMemberCardId);
        String url = "http://api.nsrjlb.com/crm/memCard/discharge";
        SysCompany sysCompany = sysCompanyDbService.selectSysCompanyById(userAccount.getCompanyId());
        /*customerProductDetailMemberCard.setMemberCardId(customerMemberCard.getMemberCardId());
        customerProductDetailMemberCard.setMemberCardNumber(customerMemberCard.getMemberCardNumber());
        customerProductDetailMemberCard.setMemberCardPassword(customerMemberCard.getMemberCardPassword());
        customerProductDetailMemberCard.setStartTm(customerMemberCard.getStartTm());
        customerProductDetailMemberCard.setEndTm(customerMemberCard.getEndTm());*/

        Customer customer = customerDbService.selectCustomerById(customerProductDetailMemberCard.getCustomerId());
        String req = "product=" + customerProductDetailMemberCard.getMemberProductCode();
        req += "&id=" + customerProductDetailMemberCard.getFinishOrderProductNum();
        if (sysCompany != null) {
            req += "&firm=" + sysCompany.getCompanyName() + "&pid=" + sysCompany.getCompanyId();
        } else {
            req += "&firm=&pid=";
        }
        //req +=
        if (!StringUtils.isBlank(customer.getContactPersonPhone())) {
            req += "&mobile=" + customer.getContactPersonPhone();
        } else {
            req += "&mobile=";
        }

        System.out.println(req);
        String res = post(url, req);
        System.out.println(res);
        if (res != null) {
            JSONObject json = JSON.parseObject(res);
            String msg = json.getString("msg");
            if ("发卡成功".equals(msg)) {
                JSONObject jsonObj = json.getJSONObject("data");//获取json数组中的data项
                String userInfo = jsonObj.getString("userInfo");
                CustomerCardVO customerCardVO = JSONObject.parseObject(userInfo, CustomerCardVO.class);
                customerProductDetailMemberCard.setMemberCardId(customerCardVO.getUserid()); //crm的id
                customerProductDetailMemberCard.setMemberCardNumber(customerCardVO.getUsername());
                customerProductDetailMemberCard.setMemberCardPassword(customerCardVO.getPassword());
                customerProductDetailMemberCard.setStartTm(customerCardVO.getRuhuidata());
                customerProductDetailMemberCard.setEndTm(customerCardVO.getYouxiaodata());
                customerProductDetailMemberCard.setCreatePeopleId(userAccount.getAccountId());
                customerProductDetailMemberCard.setCreateTm(new Date());
                customerProductDetailMemberCard.setUpdatePeopleId(userAccount.getAccountId());
                customerProductDetailMemberCard.setUpdateTm(new Date());
                customerProductDetailMemberCard.setAccountId(userAccount.getAccountId());
                Boolean result = customerDbService.addCustomerProductDetailMemberCard(customerProductDetailMemberCard);
                if (result) {
                    String throughTrain = jsonObj.getString("throughTrain");
                    if (!StringUtils.isBlank(throughTrain)) {
                        List<ThroughTrainVO> array2 = JSONArray.parseArray(throughTrain, ThroughTrainVO.class);
                        for (ThroughTrainVO vo : array2) {
                            CustomerProductDetailThroughTrainTax customerProductDetailThroughTrainTax = new CustomerProductDetailThroughTrainTax();
                            customerProductDetailThroughTrainTax.setThroughTrainTaxId(CommonUtils.getGUID());
                            customerProductDetailThroughTrainTax.setThroughTrainTaxCrmId(vo.getUserid());
                            customerProductDetailThroughTrainTax.setMemberCardNumber(vo.getUsername());
                            customerProductDetailThroughTrainTax.setMemberCardPassword(vo.getPassword());
                            customerProductDetailThroughTrainTax.setCreatePeopleId(userAccount.getAccountId());
                            customerProductDetailThroughTrainTax.setCreateTm(new Date());
                            customerProductDetailThroughTrainTax.setUpdatePeopleId(userAccount.getAccountId());
                            customerProductDetailThroughTrainTax.setUpdateTm(new Date());
                            customerProductDetailThroughTrainTax.setCustomerProductDetailMemberCardId(customerProductDetailMemberCardId);
                            customerDbService.addCustomerProductDetailThroughTrainTax(customerProductDetailThroughTrainTax);
                        }
                    }

                    return customerProductDetailMemberCardId;
                } else {
                    return "ERROR";
                }

            } else {
                return "ERROR";
            }


        }


        return "ERROR";




        /*
        CustomerMemberCard customerMemberCard = memberCardDbService.selectMemberShipCard();
        if(customerMemberCard != null) {


            customerMemberCard.setMemberCardStatus("1");
            customerMemberCard.setCompanyId(userAccount.getCompanyId());
            customerMemberCard.setUpdatePeopleId(userAccount.getAccountId());
            customerMemberCard.setUpdateTm(new Date());
            customerMemberCard.setCustomerId(customerProductDetailMemberCard.getCustomerId());
            List<Contact> list = contactDbService.contactByCustomerIdList(customerProductDetailMemberCard.getCustomerId());
            if (list != null && list.size() > 0) {
                customerMemberCard.setContactId(list.get(0).getContactId());
            }
            Boolean result = memberCardDbService.updateCustomerMemberCard(customerMemberCard);
        }else {
            return "MC001";
        }*/


    }

    public String post(String urlStr, String xmlInfo) {
        String obj = null;

        CloseableHttpClient httpclient = HttpClients.createDefault();

        HttpPost httppost = new HttpPost(urlStr);
        httppost.addHeader("Content-type", "application/x-www-form-urlencoded");
        //httppost.setHeader("Accept", "application/json");
        try {
            StringEntity s = new StringEntity(xmlInfo, Charset.forName("UTF-8"));
            s.setContentEncoding("UTF-8");
            httppost.setEntity(s);
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null)
                    obj = EntityUtils.toString(entity, "UTF-8");
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return obj;
    }

    /**
     * 通过会员卡id查询会员卡信息
     *
     * @param customerProductDetailMemberCardId 会员卡id
     * @return
     */
    @Override
    public CustomerProductDetailMemberCard getCustomerProductDetailMemberCardById(String customerProductDetailMemberCardId) {
        return customerDbService.getCustomerProductDetailMemberCardById(customerProductDetailMemberCardId);
    }

    /**
     * 组装产品详细信息
     *
     * @param customerProductDetailVO 产品信息类
     * @param finishOrderProductNum   产品号
     * @param accountId               用户id
     * @param customerId              客户id
     * @return
     */
    public CustomerProductDetail zzCustomerProductDetail(CustomerProductDetailVO customerProductDetailVO, String finishOrderProductNum, String accountId, String customerId) {
        CustomerProductDetail customerProductDetail = new CustomerProductDetail();
        customerProductDetail.setCustomerProductDetailId(CommonUtils.getGUID());
        customerProductDetail.setMemberProductCode(customerProductDetailVO.getMemberProductCode());
        customerProductDetail.setFinishOrderProductNum(finishOrderProductNum);
        customerProductDetail.setMemberCardName(customerProductDetailVO.getMemberCardName());
        customerProductDetail.setSellingCardPrice(customerProductDetailVO.getSellingCardPrice());
        customerProductDetail.setServiceNumber(customerProductDetailVO.getServiceNumber());
        customerProductDetail.setProductMembershipLevel(customerProductDetailVO.getProductMembershipLevel());
        customerProductDetail.setCreatePeopleId(accountId);
        customerProductDetail.setCreateTm(new Date());
        customerProductDetail.setUpdatePeopleId(accountId);
        customerProductDetail.setUpdateTm(new Date());
        customerProductDetail.setAccountId(accountId);
        customerProductDetail.setCustomerId(customerId);
        return customerProductDetail;
    }


    /**
     * @Description: 根据产品编码查询客户信息
     * @Param: [productCode]
     * @Return: java.util.List<com.crm.model.vo.customerManager.FinishOrderCustomerVO>
     * @Author: lixq-fs
     * @Date: 2021/6/2
     **/
    @Override
    public List<FinishOrderCustomerVO> selectCustomersByProductCode(String productCode) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        List<FinishOrderCustomerVO> list =
                finishOrderDBservice.selectCustomersByProductCode(productCode, userAccount.getAccountId());
        return Optional.ofNullable(list).orElse(Lists.newArrayList());
    }


    /**
     * @Description: 根据客户id获取客户下产品信息
     * @Param: [customerId]
     * @Return: java.util.List<com.crm.model.vo.returnMoney.ProductOfCustomerVO>
     * @Author: lixq-f
     * @Date: 2021/6/3
     **/
    @Override
    public List<ProductOfCustomerVO> selectProductsByCustomerId(String customerId, String productCode) {
        if (StringUtils.isEmpty(customerId) || StringUtils.isEmpty(productCode)) {
            return Lists.newArrayList();
        }
        List<ProductOfCustomerVO> voList =
                finishOrderDBservice.selectProductsByCustomerId(customerId, productCode);
        return Optional.ofNullable(voList).orElse(Lists.newArrayList());
    }

    /**
     * 信息错误分页
     *
     * @param pageIndex
     * @param pageSize
     * @param customerQO
     * @param sortName
     * @param sortOrder
     * @return
     * @Author renshaorong
     * @Date 2021/7/12
     */
    @Override
    public DhPageInfo<CustomerVO> selectInfomationErrorList(Integer pageIndex, Integer pageSize, CustomerQO customerQO, String sortName, String sortOrder) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        //增加删除状态查询条件(0:正常;1:已删除)
        customerQO.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());

        StringBuilder order = new StringBuilder();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch (sortName) {
                case "createTm": {
                    order.append("create_tm ").append(sortOrder);
                }
                break;
                default:
                    break;
            }
        }
        //筛选信息错误
        customerQO.setMemberErrorData(1);
        List<CustomerVO> customerList = customerDbService.selectInfomationErrorList(customerQO, order.toString());
        PageInfo<CustomerVO> pageInfo = new PageInfo<CustomerVO>(customerList);
        return new DhPageInfo<CustomerVO>(pageInfo, customerList);
    }

    /**
     * 更新给定字段，字段为空时不更新
     *
     * @param customer
     * @return
     * @Author renshaorong
     * @Date 2021/7/12
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public String updateCustomer(Customer customer) {
        Customer errorCustomer = customerDbService.selectCustomerById(customer.getCustomerId());
        if (!customer.getCustomerName().equals(errorCustomer.getCustomerName()) && !customer.getUnifiedSocialCreditCode().equals(errorCustomer.getUnifiedSocialCreditCode())) { //判断是否客户名及社会信用代码同时修改了
            return ResponseCodeEnum.EDIT_TWO_SAME_TIME.getResponseCode();
        }

        //调用企查查企业工商核验接口
        String verification = clueService.getVerification(customer.getCustomerName(), customer.getUnifiedSocialCreditCode());
        if (!"200".equals(verification)) {
            //失败
            return ResponseCodeEnum.CLUE_QCC_CHECK.getResponseCode();
        }

        customer.setMemberErrorData(0);
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        if (!customer.getCustomerName().equals(errorCustomer.getCustomerName())) { //记录修改客户名称
            this.insertModificationRecord(12, errorCustomer.getCustomerName(), customer.getCustomerName(), errorCustomer.getCustomerId(), userAccount.getAccountId());
        }
        if (!customer.getUnifiedSocialCreditCode().equals(errorCustomer.getUnifiedSocialCreditCode())) { //记录修改客户名称
            this.insertModificationRecord(13, errorCustomer.getUnifiedSocialCreditCode(), customer.getUnifiedSocialCreditCode(), errorCustomer.getCustomerId(), userAccount.getAccountId());
        }
        return customerDbService.updateByPrimaryKeySelective(customer) ? ResponseCodeEnum.OK.getResponseCode() : ResponseCodeEnum.ERROR.getResponseCode();
    }




    /**
     * 通过登录人查询企业客户
     *
     * @Author renshaorong
     * @Date 2021/7/13
     */
    @Override
    public List<Customer> getCompCustomerList(String order) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        List<Customer> list = customerDbService.getCompCustomerList(userAccount.getAccountId(), order);
        return list;
    }

    @Override
    public Map<String, Object> getPoolType(String customerId) {
        return customerDbService.getPoolType(customerId);
    }

    /**
     * 往Redis里批量添加客户信息
     *
     * @param
     * @return {@link }
     * @Author pym
     * @Date 2021/7/21 13:29
     */
    @Override
    public void insertCustomerToRedis() {
        List<Customer> customerList = customerDbService.getAllCustomerWhereNameAndCreditCodeNotNull();
        customerRedisService.addCustomerToRedis(customerList);
    }

    /**
     * 客服管理-客户详情-会员卡信息
     * @param customerId 客户id
     * @return
     */
    @Override
    public DhPageInfo<CustomerProductDetailMemberCard> selectCardByCustomerId(String customerId,String cardNumber,Integer pageIndex,Integer pageSize,String sortName,String sortOrder) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }


        List<CustomerProductDetailMemberCard> cardList = customerProductDetailMemberCardDbService.selectCardByCustomerId(customerId,cardNumber);

        PageInfo<CustomerProductDetailMemberCard> pageInfo = new PageInfo<CustomerProductDetailMemberCard>(cardList);
        return new DhPageInfo<CustomerProductDetailMemberCard>(pageInfo, cardList);
    }

    /**
     * 俺的客户列表
     * @param pageIndex
     * @param pageSize
     * @param customerQO
     * @param sortName
     * @param sortOrder
     * @return
     */
    @Override
    public DhPageInfo<CustomerVO> meCustomerList(Integer pageIndex, Integer pageSize, CustomerQO customerQO, String sortName, String sortOrder) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        StringBuilder order = new StringBuilder();
        switch (sortName) {
            case "customerWallet": {
                order.append("customer_wallet ").append(sortOrder);//钱包余额
            }
            break;
            case "customerName": {
                order.append("customer_name ").append(sortOrder);//钱包余额
            }
            break;
            default:
                break;
        }
        customerQO.setAccountId(userAccount.getAccountId());
        List<CustomerVO> cardList = customerDbService.selectMeCustomerList(customerQO,order.toString());
        PageInfo<CustomerVO> pageInfo = new PageInfo<CustomerVO>(cardList);
        return new DhPageInfo<CustomerVO>(pageInfo, cardList);
    }

    /**
     * 往修改记录表里添加数据
     *
     * @param code       字段名代表
     * @param beforeName 修改前
     * @param afterName  修改后F
     * @param customerId 客户id
     * @param accountId  用户id
     */
    public void insertModificationRecord(int code, String beforeName, String afterName, String customerId, String accountId) {
        ModificationRecord modificationRecord = new ModificationRecord();
        String modificationRecordId = CommonUtils.getGUID();
        modificationRecord.setModificationRecordId(modificationRecordId);
        modificationRecord.setModificationName(ModificationEnum.getNameByCode(code));
        modificationRecord.setBeforeModification(beforeName);
        modificationRecord.setAfterModification(afterName);
        modificationRecord.setVerifyStatus(3);
        modificationRecord.setCreatePeopleId(accountId);
        modificationRecord.setCreateTm(new Date());
        modificationRecord.setUpdatePeopleId(accountId);
        modificationRecord.setUpdateTm(new Date());
        modificationRecord.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        modificationRecord.setCustomerId(customerId);
        customerPoolDbService.addModificationRecord(modificationRecord);
    }


    /**
     * 内训部-客户公海
     * @Author renshaorong
     * @Date 2021/9/6
     * @param pageIndex
     * @param pageSize
     * @param customerQO
     * @param sortName
     * @param sortOrder
     * @return
     */
    @Override
    public DhPageInfo<CustomerVO> selectCustomerVOListForInT(Integer pageIndex, Integer pageSize, CustomerQO customerQO, String sortName, String sortOrder) {

        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        //增加删除状态查询条件(0:正常;1:已删除)
        customerQO.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());

        StringBuilder order = new StringBuilder();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch (sortName) {
                case "customerName": {
                    order.append("customer_name ").append(sortOrder);//客户名称
                }
                break;
                case "tag": {
                    order.append("tag ").append(sortOrder);
                }
                break;
                default:
                    break;
            }
        }
        List<CustomerVO> customerList = customerDbService.selectCustomerVOListForInT(customerQO, order.toString());
        PageInfo<CustomerVO> pageInfo = new PageInfo<CustomerVO>(customerList);
        return new DhPageInfo<CustomerVO>(pageInfo, customerList);
    }

    /**
     * 内训部-我的客户
     * @Author renshaorong
     * @Date 2021/9/6
     * @param pageIndex
     * @param pageSize
     * @param customerQO
     * @param sortName
     * @param sortOrder
     * @return
     */
    @Override
    public DhPageInfo<CustomerVO> selectCustomerVOListByOwner(Integer pageIndex, Integer pageSize, CustomerQO customerQO, String sortName, String sortOrder) {

        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();

        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        Integer dateUnit = 0;
        if (!StringUtils.isBlank(customerQO.getDateType())) {
            if ("thisWeek".equals(customerQO.getDateType())) {
                //本周
                dateUnit = 1;
            }
            if ("thisMonth".equals(customerQO.getDateType())) {
                //本月
                dateUnit = 2;
            }
            if ("thisYear".equals(customerQO.getDateType())) {
                //本年
                dateUnit = 3;
            }
        }

        //增加删除状态查询条件(0:正常;1:已删除)
        customerQO.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());

        StringBuilder order = new StringBuilder();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch (sortName) {
                case "customerName": {
                    order.append("cc.customer_name ").append(sortOrder);//客户名称
                }
                break;
                default:
                    break;
            }
        }
        List<CustomerVO> customerList = customerDbService.selectCustomerVOListByOwner(customerQO,userAccount.getAccountId(),dateUnit, order.toString());
        PageInfo<CustomerVO> pageInfo = new PageInfo<CustomerVO>(customerList);
        return new DhPageInfo<CustomerVO>(pageInfo, customerList);
    }

    /**
     * 内训部-新增客户
     * @param customerAddQO
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Map<String, String> addCustomerinT(CustomerAddQO customerAddQO) {
        Map<String, String> map = new HashMap<String, String>();
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        String companyId = userAccount.getCompanyId();
        String accountId = userAccount.getAccountId();
        CustomerPool customerPool = null;
        //判断当前账号是否超出200
        Integer integer = customerUserDbService.selectCountByOwner(accountId);
        if(integer >= 200){
            map.put("code", "C00004");
            map.put("customerId", "");
            //超出我的客户容量
            return map;
        }
        //客户名称
        String customerName = CommonUtils.removeCharacters(customerAddQO.getCustomerName()).replaceAll("\\(", "（").replaceAll("\\)", "）");
        customerAddQO.setCustomerName(customerName);
        //统一社会信用代码
        String unifiedSocialCreditCode = customerAddQO.getUnifiedSocialCreditCode();
        //通过社会信用代码调用企查查的企业工商信息核验接口
        String responseCode = clueService.getVerification(customerName, unifiedSocialCreditCode);
        if (!"200".equals(responseCode)) {
            System.out.println("查询工商核验信息失败··········");
            map.put("code", "C00201");//表示核验失败
            map.put("message", "输入的企业信息有误，请核实！");
            return map;
        }
        //根据公司id查询客户池信息
        if (StringUtils.isNotBlank(companyId)) {
            customerPool = customerPoolDbService.selectCustomerPoolCompanyId(companyId);
        }
        if (customerPool == null) {
            //所属公司对应的全国公有池不存在
            map.put("code", "C00003");
            map.put("customerId", "");
            return map;
        }
        //客户池容量
        int capacity = customerPool.getCapacity();
        String customerPoolId = customerPool.getCustomerPoolId();
        customerAddQO.setCustomerPoolId(customerPoolId);

        //查询客户池已经存在的客户数
        long count = customerDbService.selectCustomerCount(customerPoolId);
        if (count < capacity) {
            Boolean result = customerRelationDbService.selectCustomerRelationByName(customerName);
            if (result) {//客户关联表已存在，客户名称已关联客户
                map.put("code", "C00005");
                map.put("customerId", "");
                return map;
            }
            Boolean isCustomerRepeat = customerDbService.selectCustomerIfRepeated(customerName, unifiedSocialCreditCode);
            if (!isCustomerRepeat) {
                Customer customer = getCustomer(customerAddQO);
                customer.setAccountId(null);
                customerDbService.insertCustomer(customer);
                customerRedisService.setCustomerByNameAndCode(customer);//将客户信息插入Redis

                //3.领取客户
                CustomerUser customerUser = new CustomerUser();
                customerUser.setCustomerId(customer.getCustomerId());
                customerUser.setOwnerId(accountId);
                customerUser.setCreatePeopleId(accountId);
                customerUser.setCreateTm(new Date());
                customerUser.setDeleteStatus((short)0);
                customerUser.setCustomerUserId(CommonUtils.getGUID());
                Boolean insertSelective = customerUserDbService.insertSelective(customerUser);
                if(insertSelective){
                    map.put("code", "C00000");
                    map.put("customerId", customer.getCustomerId());
                }else{
                    map.put("code", "NX0001");
                    map.put("customerId", "");
                }
                // sync ES
                syncES(customer,accountId,"新增企业客户");

                return map;
            } else {
                map.put("code", "C00002");
                map.put("customerId", "");
                //客户名称和统一社会信用代码已存在
                return map;
            }
        } else {
            map.put("code", "C00001");
            map.put("customerId", "");
            //超出客户池容量
            return map;
        }

    }

    @Override
    public DhPageInfo<FinishOrderProductVO> selectFinishOrderProductList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder,String customerId) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        //排序
        StringBuilder order = new StringBuilder();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch (sortName) {
                case "createTm": {
                    order.append("f.create_tm ").append(sortOrder);//创建时间
                }
                break;
                default:
                    break;
            }
        }
        List<FinishOrderProductVO> retustList=finishOrderDBservice.selectProductSceneList(order.toString(),customerId);
        PageInfo<FinishOrderProductVO> page =new PageInfo(retustList);
        return new DhPageInfo<FinishOrderProductVO>(page,retustList);
    }

    /**
     * 获取内训下的客户
     * @return
     */
    @Override
    public List<CustomerVO> getCustomerUserList() {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        return customerDbService.getCustomerUserList(userAccount.getAccountId());
    }

    /**
     * changeProductXcchHychGdb
     *  产品明细 --兑换
     * @Author wangpeng
     * @Date 2021/10/27
     * @param vo
     * @return
     */
    @Override
    public Map changeProductXcchHychGdb(exchangeVO vo) {
        //总回信息
        HashMap<Object, Object> map = new HashMap<>();
        //根据产品号，订单id查询
        CustomerMemberCardDetailVO customerMemberCardDetailVO = customerDbService.selectCustomerMemberCardDetailByProductOrderId(vo.getProductOrderId(),vo.getFinishOrderProductNum());
        if(customerMemberCardDetailVO == null){
            map.put("code", 1);
            map.put("msg", "没有会员，请先去申请会员卡");
            return map;
        }
        //会员卡卡号
        String memberCardNumber = customerMemberCardDetailVO.getMemberCardNumber();
        //获取用户信息
        UserAccount user = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        SysCompany sysCompany = sysCompanyDbService.selectSysCompanyById(user.getCompanyId());
        //调用 根据会员卡卡号信息查看现场或行业会天数
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("card", memberCardNumber);
        String res = HttpUtil.post("http://api.nsrjlb.com/crm/MemCard/getCardFrequency", paramMap);
        JSONObject json = JSON.parseObject(res);
        Integer de = json.getInteger("code");
        String data = json.getString("data");
        CardFrequencyVO v = JSONArray.parseObject(data, CardFrequencyVO.class);
        String isVipnum = v.getIsVipnum();
        //现场参会
        if (vo.getType() == 1) {
            if (de != null && de == 1) {
                //查兑换记录表是否有记录
                List<CustomerChangeCourseRecordVO> customerChangeCourseRecordVO = customerDbService.selectChangeCourseCecordList(memberCardNumber);
                if (customerChangeCourseRecordVO.size() <= 0) {
                    Double num1 = 0.0;
                    Double day = Double.valueOf(vo.getDays());
                    if (v.getNum1() != null) {
                        num1 = Double.valueOf(v.getNum1());
                    }
                    if (day <= num1) {
                        String xcch = String.valueOf(num1);
                        String hyhsycs = v.getNum7();
                        String memberCardId = customerMemberCardDetailVO.getCustomerProductDetailMemberCardId();
                        String userName = user.getUserName();
                        String contractId = customerMemberCardDetailVO.getContractId();
                        String accountId = user.getAccountId();
                        String memberProductCode = customerMemberCardDetailVO.getMemberProductCode();
                        String orderNumber = customerMemberCardDetailVO.getOrderNumber();
                        String xcchKc = String.valueOf(vo.getDays());
                        String hyhsycsKc = "0";
                        String contractNumber = customerMemberCardDetailVO.getContractNumber();
                        String changeCourseType = "0";
                        String gdbChangeXcch = null;
                        String productCode =null;
                        String productName = null;
                        //新增记录到兑换记录表
                        addCustomerChangeCourseRecord(xcch, hyhsycs, memberCardNumber, memberCardId, userName, vo.getChangeCourseTitle(),
                                vo.getProductOrderId(), contractId, accountId, productCode,
                                productName, memberProductCode, vo.getRuleNumber(), vo.getCourseProductCode(),
                                orderNumber, vo.getChangeProductCode(), xcchKc, hyhsycsKc, vo.getFinishOrderProductNum(),
                                vo.getFinishProductName(), user.getCompanyId(), contractNumber, sysCompany.getCompanyName(),
                                vo.getUploadId(), changeCourseType,vo.getFinishOrderProductId(),vo.getProductId(),gdbChangeXcch,vo.getProductType(),
                                vo.getRuleTitle());
                    } else {
                        map.put("code", 1);
                        map.put("msg", "现场天数不足");
                        return map;
                    }
                } else {
                    map.put("code", 1);
                    map.put("msg", "已兑换课程还未审批");
                    return map;
                }
            }else{
                map.put("code", 1);
                map.put("msg", "参数错误,请重试。");
                return map;
            }
        }

        //行业会
        if (vo.getType() == 2) {
            if (de != null && de == 1) {
                //查兑换记录表是否有记录
                List<CustomerChangeCourseRecordVO> customerChangeCourseRecordVO = customerDbService.selectChangeCourseCecordList(memberCardNumber);
                if (customerChangeCourseRecordVO.size() <= 0) {
                    Integer num7 = 0;
                    if (v.getNum7() != null) {
                        num7 = Integer.valueOf(v.getNum7());
                    }
                    if (vo.getDays() <= num7) {
                        String xcch = v.getNum1();
                        String hyhsycs = String.valueOf(num7);
                        String memberCardId = customerMemberCardDetailVO.getCustomerProductDetailMemberCardId();
                        String userName = user.getUserName();
                        String contractId = customerMemberCardDetailVO.getContractId();
                        String accountId = user.getAccountId();
                        String memberProductCode = customerMemberCardDetailVO.getMemberProductCode();
                        String orderNumber = customerMemberCardDetailVO.getOrderNumber();
                        String xcchKc = "0";
                        String hyhsycsKc = String.valueOf(vo.getDays());
                        String contractNumber = customerMemberCardDetailVO.getContractNumber();
                        String changeCourseType = "1";
                        String gdbChangeXcch = null;
                        String productCode =null;
                        String productName = null;
                        //新增记录到兑换记录表
                        addCustomerChangeCourseRecord(xcch, hyhsycs, memberCardNumber, memberCardId, userName, vo.getChangeCourseTitle(),
                                vo.getProductOrderId(), contractId, accountId, productCode,
                                productName, memberProductCode, vo.getRuleNumber(), vo.getCourseProductCode(),
                                orderNumber, vo.getChangeProductCode(), xcchKc, hyhsycsKc, vo.getFinishOrderProductNum(),
                                vo.getFinishProductName(), user.getCompanyId(), contractNumber, sysCompany.getCompanyName(),
                                vo.getUploadId(), changeCourseType,vo.getFinishOrderProductId(),vo.getProductId(),gdbChangeXcch,
                                vo.getProductType(),vo.getRuleTitle());
                    } else {
                        map.put("code", 1);
                        map.put("msg", "行业会次数不足");
                        return map;
                    }
                } else {
                    map.put("code", 1);
                    map.put("msg", "已兑换课程还未审批");
                    return map;
                }
            }else{
                map.put("code", 1);
                map.put("msg", "参数错误,请重试。");
                return map;
            }
        }

        //高端班兑换课程
        if (vo.getType() == 3){
            String ruleNumber = vo.getRuleNumber();
            String[] ruleNumbers = ruleNumber.split(",");
            String[] highCode = vo.getHighCode();
            String[] highName = vo.getHighName();
            String[] highProductCode = vo.getHighProductCode();
            String[] highProductName = vo.getHighProductName();
            Integer[] price =(Integer[]) ConvertUtils.convert(vo.getProductOriginalPrice(), Integer.class);
            String productTypes = vo.getProductType();
            String[] productType = productTypes.split(",");
            for (int i=0;i<highProductCode.length;i++){
                boolean equals = vo.getChangeProductCode().equals(highProductCode[i]);
                if(equals == false){
                    map.put("code", 1);
                    map.put("msg", "课程和会员卡类型不一致,请从新选择。");
                    return map;
                }
            }
            Integer num = 0;
            for (int i=0;i<price.length;i++){
                num +=price[i];
            }
            //根据id查产品原价
            Integer originalPrice = 0;
            if(vo.getFinishProductName().equals("会员金卡")){
                //会员金卡价值39800   高端班能使用13800  sNQxHw
                originalPrice = 13800;
            }else if (vo.getFinishProductName().equals("会员皇冠卡")){
                //会员皇冠卡价值59800    高端班能使用29800  AjbceD
                originalPrice = 29800;
            }else if (vo.getFinishProductName().equals("智臻会员")){
                //智臻会员价值99000   高端班能使用39800  c2zwRr
                originalPrice = 39800;
            }else if (vo.getFinishProductName().equals("会员白金卡")){
                //会员白金卡价值99000   高端班能使用39800  xmXBZM
                originalPrice = 39800;
            }
            if(num < originalPrice) {
                if (de != null && de == 1) {
                    //查兑换记录表是否有记录
                    List<CustomerChangeCourseRecordVO> customerChangeCourseRecordVO = customerDbService.selectChangeCourseCecordList(memberCardNumber);
                    if (customerChangeCourseRecordVO.size() <= 0) {
                        if (isVipnum.equals("1")) {
                            String xcch = v.getNum1();
                            String hyhsycs = v.getNum7();
                            String memberCardId = customerMemberCardDetailVO.getCustomerProductDetailMemberCardId();
                            String userName = user.getUserName();
                            String contractId = customerMemberCardDetailVO.getContractId();
                            String accountId = user.getAccountId();
                            String memberProductCode = customerMemberCardDetailVO.getMemberProductCode();
                            String orderNumber = customerMemberCardDetailVO.getOrderNumber();
                            String xcchKc = "0";
                            String hyhsycsKc = "0";
                            String contractNumber = customerMemberCardDetailVO.getContractNumber();
                            String changeCourseType = "2";
                            String gdbChangeXcch = null;
                            String finishOrderProductId = vo.getFinishOrderProductId();
                            //新增记录到兑换记录表
                            if(highProductCode.length  == productType.length){
                                for (int i = 0; i < highProductCode.length; i++) {
                                    addCustomerChangeCourseRecord(xcch, hyhsycs, memberCardNumber, memberCardId, userName, highName[i],
                                            vo.getProductOrderId(), contractId, accountId, highProductCode[i],
                                            highProductName[i], memberProductCode, ruleNumbers[i], highCode[i],
                                            orderNumber, vo.getChangeProductCode(), xcchKc, hyhsycsKc, vo.getFinishOrderProductNum(),
                                            vo.getFinishProductName(), user.getCompanyId(), contractNumber, sysCompany.getCompanyName(),
                                            vo.getUploadId(), changeCourseType,vo.getFinishOrderProductId(),vo.getProductId(),
                                            gdbChangeXcch,productType[i],vo.getRuleTitle());
                                }
                            }else {
                                for (int i = 0; i < highProductCode.length; i++) {
                                    addCustomerChangeCourseRecord(xcch, hyhsycs, memberCardNumber, memberCardId, userName, highName[i],
                                            vo.getProductOrderId(), contractId, accountId, highProductCode[i],
                                            highProductName[i], memberProductCode, ruleNumbers[i], highCode[i],
                                            orderNumber, vo.getChangeProductCode(), xcchKc, hyhsycsKc, vo.getFinishOrderProductNum(),
                                            vo.getFinishProductName(), user.getCompanyId(), contractNumber, sysCompany.getCompanyName(),
                                            vo.getUploadId(), changeCourseType,vo.getFinishOrderProductId(),vo.getProductId(),
                                            gdbChangeXcch,productTypes,vo.getRuleTitle());
                                }
                            }

                        } else {
                            map.put("code", 1);
                            map.put("msg", "高端班已使用。");
                            return map;
                        }
                    } else {
                        map.put("code", 1);
                        map.put("msg", "已兑换课程还未审批。");
                        return map;
                    }
                } else {
                    map.put("code", 1);
                    map.put("msg", "参数错误,请重试。");
                    return map;
                }
            }else {
                map.put("code", 1);
                map.put("msg", "选择课程的价格大于卡价格，请从新选择。");
                return map;
            }

        }

        //高端班兑换现场天数
        if (vo.getType() == 4) {
            if (vo.getChangeProductCode().equals(vo.getCourseProductCode())) {
                if (de != null && de == 1) {
                    //查兑换记录表是否有记录
                    List<CustomerChangeCourseRecordVO> customerChangeCourseRecordVO = customerDbService.selectChangeCourseCecordList(memberCardNumber);
                    if (customerChangeCourseRecordVO.size() <= 0) {
                        if (isVipnum.equals("1")) {
                            String xcch = v.getNum1();
                            String hyhsycs = v.getNum7();
                            String memberCardId = customerMemberCardDetailVO.getCustomerProductDetailMemberCardId();
                            String userName = user.getUserName();
                            String contractId = customerMemberCardDetailVO.getContractId();
                            String accountId = user.getAccountId();
                            String memberProductCode = customerMemberCardDetailVO.getMemberProductCode();
                            String orderNumber = customerMemberCardDetailVO.getOrderNumber();
                            String xcchKc = "0";
                            String hyhsycsKc = "0";
                            String contractNumber = customerMemberCardDetailVO.getContractNumber();
                            String changeCourseType = "3";
                            String gdbChangeXcch = String.valueOf(vo.getDays());
                            String productCode =null;
                            String productName = null;
                            //新增记录到兑换记录表
                            addCustomerChangeCourseRecord(xcch, hyhsycs, memberCardNumber, memberCardId, userName, vo.getChangeCourseTitle(),
                                    vo.getProductOrderId(), contractId, accountId, productCode,
                                    productName, memberProductCode, vo.getRuleNumber(), vo.getCourseProductCode(),
                                    orderNumber, vo.getChangeProductCode(), xcchKc, hyhsycsKc, vo.getFinishOrderProductNum(),
                                    vo.getFinishProductName(), user.getCompanyId(), contractNumber, sysCompany.getCompanyName(),
                                    vo.getUploadId(), changeCourseType,vo.getFinishOrderProductId(),vo.getProductId(),gdbChangeXcch,
                                    vo.getProductType(),vo.getRuleTitle());
                        } else {
                            map.put("code", 1);
                            map.put("msg", "高端班已使用。");
                            return map;
                        }
                    } else {
                        map.put("code", 1);
                        map.put("msg", "已兑换课程还未审批。");
                        return map;
                    }
                } else {
                    map.put("code", 1);
                    map.put("msg", "参数错误,请重试。");
                    return map;
                }
            }else{
                map.put("code", 1);
                map.put("msg", "请选择正确的会员卡类型。");
                return map;
            }
        }
        //现场兑换行业会
        if (vo.getType() == 5) {
            if (de != null && de == 1) {
                //查兑换记录表是否有记录
                List<CustomerChangeCourseRecordVO> customerChangeCourseRecordVO = customerDbService.selectChangeCourseCecordList(memberCardNumber);
                if (customerChangeCourseRecordVO.size() <= 0) {
                    Double num1 = 0.0;
                    if (v.getNum1() != null) {
                        num1 = Double.valueOf(v.getNum1());
                    }
                    Integer num7 = 0;
                    if (v.getNum7() != null) {
                        num7 = Integer.valueOf(v.getNum7());
                    }
                    Double siteDays = Double.valueOf(vo.getSiteDays());
                    if (siteDays <= num1) {
                        String xcch = String.valueOf(num1);
                        String hyhsycs = String.valueOf(num7);
                        String memberCardId = customerMemberCardDetailVO.getCustomerProductDetailMemberCardId();
                        String userName = user.getUserName();
                        String contractId = customerMemberCardDetailVO.getContractId();
                        String accountId = user.getAccountId();
                        String memberProductCode = customerMemberCardDetailVO.getMemberProductCode();
                        String orderNumber = customerMemberCardDetailVO.getOrderNumber();
                        String xcchKc = String.valueOf(vo.getSiteDays());
                        String hyhsycsKc = String.valueOf(vo.getIndustryNumber());
                        String contractNumber = customerMemberCardDetailVO.getContractNumber();
                        String changeCourseType = "4";
                        String gdbChangeXcch = null;
                        String productCode =null;
                        String productName = null;
                        //新增记录到兑换记录表
                        addCustomerChangeCourseRecord(xcch, hyhsycs, memberCardNumber, memberCardId, userName, vo.getChangeCourseTitle(),
                                vo.getProductOrderId(), contractId, accountId, productCode,
                                productName, memberProductCode, vo.getRuleNumber(), vo.getCourseProductCode(),
                                orderNumber, vo.getChangeProductCode(), xcchKc, hyhsycsKc, vo.getFinishOrderProductNum(),
                                vo.getFinishProductName(), user.getCompanyId(), contractNumber, sysCompany.getCompanyName(),
                                vo.getUploadId(), changeCourseType,vo.getFinishOrderProductId(),vo.getProductId(),gdbChangeXcch,
                                vo.getProductType(),vo.getRuleTitle());
                    } else {
                        map.put("code", 1);
                        map.put("msg", "现场天数不足。");
                        return map;
                    }
                } else {
                    map.put("code", 1);
                    map.put("msg", "已兑换课程还未审批。");
                    return map;
                }
            }else{
                map.put("code", 1);
                map.put("msg", "参数错误,请重试。");
                return map;
            }
        }
        //行业会兑换现场
        if (vo.getType() == 6) {
            if (de != null && de == 1) {
                //查兑换记录表是否有记录
                List<CustomerChangeCourseRecordVO> customerChangeCourseRecordVO = customerDbService.selectChangeCourseCecordList(memberCardNumber);
                if (customerChangeCourseRecordVO.size() <= 0) {
                    Double num1 = 0.0;
                    if (v.getNum1() != null) {
                        num1 = Double.valueOf(v.getNum1());
                    }
                    Integer num7 = 0;
                    if (v.getNum7() != null) {
                        num7 = Integer.valueOf(v.getNum7());
                    }
                    if (vo.getIndustryNumber() <= num7) {
                        String xcch = String.valueOf(num1);
                        String hyhsycs = String.valueOf(num7);
                        String memberCardId = customerMemberCardDetailVO.getCustomerProductDetailMemberCardId();
                        String userName = user.getUserName();
                        String contractId = customerMemberCardDetailVO.getContractId();
                        String accountId = user.getAccountId();
                        String memberProductCode = customerMemberCardDetailVO.getMemberProductCode();
                        String orderNumber = customerMemberCardDetailVO.getOrderNumber();
                        String xcchKc = String.valueOf(vo.getSiteDays());
                        String hyhsycsKc = String.valueOf(vo.getIndustryNumber());
                        String contractNumber = customerMemberCardDetailVO.getContractNumber();
                        String changeCourseType = "5";
                        String gdbChangeXcch = null;
                        String productCode =null;
                        String productName = null;
                        //新增记录到兑换记录表
                        addCustomerChangeCourseRecord(xcch, hyhsycs, memberCardNumber, memberCardId, userName, vo.getChangeCourseTitle(),
                                vo.getProductOrderId(), contractId, accountId, productCode,
                                productName, memberProductCode, vo.getRuleNumber(), vo.getCourseProductCode(),
                                orderNumber, vo.getChangeProductCode(), xcchKc, hyhsycsKc, vo.getFinishOrderProductNum(),
                                vo.getFinishProductName(), user.getCompanyId(), contractNumber, sysCompany.getCompanyName(),
                                vo.getUploadId(), changeCourseType,vo.getFinishOrderProductId(),vo.getProductId(),gdbChangeXcch,
                                vo.getProductType(),vo.getRuleTitle());
                    } else {
                        map.put("code", 1);
                        map.put("msg", "行业会次数不足。");
                        return map;
                    }
                } else {
                    map.put("code", 1);
                    map.put("msg", "已兑换课程还未审批。");
                    return map;
                }
            }else{
                map.put("code", 1);
                map.put("msg", "参数错误,请重试。");
                return map;
            }
        }
        map.put("code", 0);
        map.put("msg", "成功");
        return map;
    }



    private void addCustomerChangeCourseRecord(String xcch, String hyhsycs, String memberCardNumber,
                                               String memberCardId, String userName, String changeCourseTitle,
                                               String productOrderId, String contractId, String accountId,
                                               String productCode, String productName, String memberProductCode,
                                               String ruleNumber, String courseProductCode, String orderNumber,
                                               String changeProductCode, String xcchKc, String hyhsycsKc,
                                               String finishOrderProductNum, String finishProductName,
                                               String companyId, String contractNumber, String companyName,
                                               String uploadId,String changeCourseType,String finishOrderProductId,
                                               String productId,String gdbChangeXcch,String productType,String ruleTitle) {
        //调用方法取uuid
        String guid = CommonUtils.getGUID();
        //获取当前时间
        Date date = new Date();
        //新增一条到兑换记录表
        CustomerChangeCourseRecordVO vo = new CustomerChangeCourseRecordVO();
        vo.setChangeCourseId(guid);
        vo.setXcch(xcch);
        vo.setHyhsycs(hyhsycs);
        vo.setMemberCardNumber(memberCardNumber);
        vo.setCustomerProductDetailMemberCardId(memberCardId);
        vo.setUserName(userName);
        vo.setChangeCourseTitle(changeCourseTitle);
        vo.setProductOrderId(productOrderId);
        vo.setContractId(contractId);
        vo.setAccountId(accountId);
        vo.setProductCode(productCode);
        vo.setProductName(productName);
        vo.setMemberProductCode(memberProductCode);
        vo.setRuleNumber(ruleNumber);
        vo.setCourseProductCode(courseProductCode);
        vo.setOrderNumber(orderNumber);
        vo.setChangeProductCode(changeProductCode);
        vo.setXcchKc(xcchKc);
        vo.setHyhsycsKc(hyhsycsKc);
        vo.setCreateTm(date);
        vo.setFinishOrderProductNum(finishOrderProductNum);
        vo.setFinishProductName(finishProductName);
        vo.setCompanyId(companyId);
        vo.setContractNumber(contractNumber);
        vo.setCompanyName(companyName);
        vo.setExamine("1");
        vo.setUploadId(uploadId);
        vo.setChangeCourseType(changeCourseType);
        vo.setFinishOrderProductId(finishOrderProductId);
        vo.setProductId(productId);
        vo.setGdbChangeXcch(gdbChangeXcch);
        vo.setProductType(productType);
        vo.setRuleTitle(ruleTitle);
        customerDbService.addCustomerChangeCourseRecord(vo);
    }

    @Override
    public String statisticalVipContractCount(char[] contractTypeArr) {
        if (null == contractTypeArr || contractTypeArr.length == 0) {
            return "参数异常！！！";
        }
        if (redisUtil.hasKey("statisticalVipContractCount")) { // 如果key已存在，则查询上月统计数据
            List<Map<String, String>> list = customerContractDbService.statisticalVipContractCount(contractTypeArr);
            String month = DateUtil.format(DateUtil.lastMonth(), "yyyy-MM");
            redisUtil.hPut("statisticalVipContractCount", month, JSONObject.toJSONString(list));
        } else { // 如果key不存在，则查询数据库中所有统计数据
            List<Map<String, Object>> mapList =
                    customerContractDbService.statisticalVipContractCountAll(contractTypeArr);
            System.out.println("---------------->" + JSONArray.toJSONString(mapList));
            mapList.forEach(map -> {
                redisUtil.hPut("statisticalVipContractCount",
                        String.valueOf(map.get("statisticalData")),
                        JSONObject.toJSONString(map.get("ContractCount")));
            });
        }
        return "数据已成功统计并存在redis中！！！";
    }

    /**
     * 用户端 - 客户公海 - 分公司 筛选列表
     * @Author pym
     * @Date  2021/11/23 11:26
     * @param pageIndex -页码
     * @param pageSize -分页大小
     * @return {@link {com.crm.common.model.DhPageInfo<com.crm.model.vo.customerManager.CustomerPoolNameVO>}}
     */
    @Override
    public DhPageInfo<CustomerPoolNameVO> selectCustomerPoolNameList(Integer pageIndex, Integer pageSize) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        List<CustomerPoolNameVO> customerPoolNameVOList = customerDbService.selectCustomerPoolNameList();
        PageInfo<CustomerPoolNameVO> pageInfo = new PageInfo<CustomerPoolNameVO>(customerPoolNameVOList);
        return new DhPageInfo<CustomerPoolNameVO>(pageInfo, customerPoolNameVOList);
    }


    /**
     * 用户端 - 客户公海 - 地区 筛选列表
     * @Author pym
     * @Date  2021/11/23 11:40
     * @param pageIndex -页码
     * @param pageSize -分页大小
     * @param customerPoolId -客户池Id
     * @return {@link {com.crm.common.model.DhPageInfo<java.lang.String>}}
     */
    @Override
    public DhPageInfo<String> selectProvinceNameList(Integer pageIndex, Integer pageSize, String customerPoolId) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        List<String> provinceNameList = customerDbService.selectProvinceNameList(customerPoolId);
        PageInfo<String> pageInfo = new PageInfo<String>(provinceNameList);
        return new DhPageInfo<String>(pageInfo, provinceNameList);
    }

    /**
     * 用户端 - 客户公海 - 标签 筛选列表
     * @Author pym
     * @Date  2021/11/23 14:21
     * @param pageIndex -页码
     * @param pageSize -分页大小
     * @param customerPoolId -客户池Id
     * @return {@link {com.crm.common.model.DhPageInfo<java.lang.String>}}
     */
    @Override
    public DhPageInfo<String> selectTagList(Integer pageIndex, Integer pageSize, String customerPoolId) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        List<String> tagList = customerDbService.selectTagList(customerPoolId);
        PageInfo<String> pageInfo = new PageInfo<String>(tagList);
        return new DhPageInfo<String>(pageInfo, tagList);
    }

    /**
     * 用户端 - 客户公海 - 客户池下客户列表
     * @Author pym
     * @Date  2021/11/23 15:42
     * @param pageIndex -页码
     * @param pageSize -分页大小
     * @param poolCustomerQO -筛选条件
     * @param sortName -排序列名字
     * @param sortOrder -排序规则(asc/desc)
     * @return {@link {com.crm.common.model.DhPageInfo<com.crm.model.vo.customerManager.PoolCustomerVO>}}
     */
    @Override
    public DhPageInfo<PoolCustomerVO> selectPoolCustomerList(Integer pageIndex, Integer pageSize, PoolCustomerQO poolCustomerQO, String sortName, String sortOrder) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        StringBuilder order = new StringBuilder();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch (sortName) {
                case "customerName": {
                    order.append("customer_name ").append(sortOrder);//客户名称
                }
                break;
                case "customerPoolName": {
                    order.append("customer_pool_name ").append(sortOrder);//客户池名称
                }
                break;
                case "provinceName": {
                    order.append("province_name ").append(sortOrder);//所在地区
                }
                break;
                case "tag": {
                    order.append("tag ").append(sortOrder);//标签
                }
                break;
                default:
                    break;
            }
        }
        List<PoolCustomerVO> poolCustomerVOList = customerDbService.selectPoolCustomerList(poolCustomerQO, order.toString());
        PageInfo<PoolCustomerVO> pageInfo = new PageInfo<PoolCustomerVO>(poolCustomerVOList);
        return new DhPageInfo<PoolCustomerVO>(pageInfo, poolCustomerVOList);
    }

    /**
     * 用户端 - 客户公海 - 行业 筛选列表
     * @Author pym
     * @Date  2021/12/10 11:00
     * @param pageIndex -页码
     * @param pageSize -分页大小
     * @param customerPoolId -客户池Id
     * @return {@link {com.crm.common.model.DhPageInfo<java.lang.String>}}
     */
    @Override
    public DhPageInfo<String> selectIndustryList(Integer pageIndex, Integer pageSize, String customerPoolId) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        List<String> industryList = customerDbService.selectIndustryList(customerPoolId);
        PageInfo<String> pageInfo = new PageInfo<String>(industryList);
        return new DhPageInfo<String>(pageInfo, industryList);
    }

}
